SQLite - replace part of a string

SqlSqlite

Sql Problem Overview


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

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

?

Sql Solutions


Solution 1 - Sql

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

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

The following should point you in the right direction.

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

Solution 2 - Sql

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

  1. Only fields containing C:\afolder will be affected anyway, no reason to check it. It's excessive.
  2. 'C:\afolder\%' will choose only fields starting with C:\afolder\ only. What if you have this path inside string?

So the correct query is just:

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

Solution 3 - Sql

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncolinView Question on Stackoverflow
Solution 1 - SqlAndrewView Answer on Stackoverflow
Solution 2 - SqlvladkrasView Answer on Stackoverflow
Solution 3 - Sqlbugmenot123View Answer on Stackoverflow