SQLite -替換字符串的一部分

[英]SQLite - replace part of a string


Is it possible using SQL in an SQLite table to replace part of a string?

是否可以在SQLite表中使用SQL替換字符串的一部分?

For example, I have a table where one of the fields holds the path to a file. Is it possible to replace parts of the string so that, e.g.

例如,我有一個表,其中一個字段保存文件的路徑。可以把繩子的一部分換掉嗎?

c:\afolder\afilename.bmp

becomes

就變成了

c:\anewfolder\afilename.bmp

?

嗎?

3 个解决方案

#1


172  

You can use the built in replace() function to perform a string replace in a query.

可以使用內置的replace()函數在查詢中執行字符串替換。

Other string manipulation functions (and more) are detailed in the SQLite core functions list

在SQLite核心函數列表中詳細介紹了其他字符串操作函數(以及更多)

The following should point you in the right direction.

下面的內容應該指向正確的方向。

UPDATE table SET field = replace( field, 'C:\afolder\', 'C:\anewfolder\' ) WHERE field LIKE 'C:\afolder\%';

更新表設置字段=替換(字段,'C:\afolder ', 'C:\anewfolder '),字段如'C:\afolder %';

#2


24  

@Andrew answer is partially correct. No need to use WHERE clause here:

@Andrew answer部分正確。此處無需使用WHERE子句:

  1. Only fields containing C:\afolder will be affected anyway, no reason to check it. It's excessive.
  2. 只有包含C:\afolder的字段會受到影響,沒有理由檢查它。這是過度。
  3. 'C:\afolder\%' will choose only fields starting with C:\afolder\ only. What if you have this path inside string?
  4. “C:\afolder\%”只會選擇以C:\afolder\%開頭的字段。如果字符串中有這個路徑呢?

So the correct query is just:

所以正確的查詢是:

UPDATE table SET field = replace( field, 'C:\afolder\', 'C:\anewfolder\');

#3


7  

And if you just want to do it in a query without lasting consequences:

如果你只是想在查詢中做而不產生持久的結果:

SELECT fieldA, replace(field, 'C:\afolder\', 'C:\anewfolder\'), fieldB FROM table;

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/05/10/725e6a304789a51e371c9c7c4b2927e.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com