Perform string replacement in SQL Server table column
When working with large data sets, it is often necessary to modify specific parts of column values, which may include replacing certain strings with new strings. For SQL Server tables, the REPLACE() function provides a simple and efficient way to perform such string replacements.
Question:
Suppose a table contains a column containing a path that needs to be partially modified. The task is to change a specific substring in all records of that column while keeping the rest of the path unchanged.
Solution:
SQL Server’s REPLACE() function is designed for this purpose. It accepts three parameters:
To replace part of a path, you can use the following update statement:
<code class="language-sql">UPDATE my_table SET path = REPLACE(path, 'oldstring', 'newstring')</code>
Usage:
For example, if column "path" contains the following values:
<code>/data/folder1/subfolder1/file1.txt /data/folder2/subfolder2/file2.txt /data/folder3/subfolder3/file3.txt</code>
And we want to replace the string "folder2" with "newfolder2", then the following update statement will achieve this:
<code class="language-sql">UPDATE my_table SET path = REPLACE(path, 'folder2', 'newfolder2')</code>
After executing this statement, the updated value in the "path" column will be:
<code>/data/folder1/subfolder1/file1.txt /data/newfolder2/subfolder2/file2.txt /data/folder3/subfolder3/file3.txt</code>
The above is the detailed content of How Can I Efficiently Replace Substrings Within a Column in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!