Advertisement
Advertisement


UPDATE and REPLACE part of a string


Question

I've got a table with two columns, ID and Value. I want to change a part of some strings in the second column.

Example of Table:

ID            Value
---------------------------------
1             c:\temp\123\abc\111
2             c:\temp\123\abc\222
3             c:\temp\123\abc\333
4             c:\temp\123\abc\444

Now the 123\ in the Value string is not needed. I tried UPDATE and REPLACE:

UPDATE dbo.xxx
SET Value = REPLACE(Value, '%123%', '')
WHERE ID <= 4

When I execute the script SQL Server does not report an error, but it does not update anything either. Why is that?

2015/09/18
1
445
9/18/2015 9:09:00 PM

Accepted Answer

You don't need wildcards in the REPLACE - it just finds the string you enter for the second argument, so the following should work:

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123\', '')
WHERE ID <=4

(I also added the \ in the replace as I assume you don't need that either)

2014/09/25
720
9/25/2014 8:09:40 AM

Try to remove % chars as below

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4
2013/06/28

To make the query run faster in big tables where not every line needs to be updated, you can also choose to only update rows that will be modified:

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <= 4
AND Value LIKE '%123%'
2016/10/12

query:

UPDATE tablename 
SET field_name = REPLACE(field_name , 'oldstring', 'newstring') 
WHERE field_name LIKE ('oldstring%');
2017/07/23

You have one table where you have date Code which is seven character something like

"32-1000"

Now you want to replace all

"32-"

With

"14-"

The SQL query you have to run is

Update Products Set Code = replace(Code, '32-', '14-') Where ...(Put your where statement in here)
2014/02/20

For anyone want to replace your script.

update dbo.[TABLE_NAME] set COLUMN_NAME= replace(COLUMN_NAME, 'old_value', 'new_value') where COLUMN_NAME like %CONDITION%

2018/10/24