Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE and REPLACE part of a string

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?

like image 215
aston_zh Avatar asked Jun 28 '13 12:06

aston_zh


People also ask

How do you update a portion of a string in SQL?

Update Part of a String in SQL Using the REPLACE() Function We could have done this simpler by using the REPLACE() function. It replaces all occurrences of a specified string value with another string value. The REPLACE function returns a string where it replaces a substring with another substring.

How do you replace a part of a value in SQL?

SQL Server REPLACE() FunctionThe REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive. Tip: Also look at the STUFF() function.


2 Answers

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

If the column to replace is type text or ntext you need to cast it to nvarchar

UPDATE dbo.xxx
SET Value = REPLACE(CAST(Value as nVarchar(4000)), '123', '')
WHERE ID <=4
like image 137
Jon Egerton Avatar answered Oct 19 '22 07:10

Jon Egerton


Try to remove % chars as below

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4
like image 73
Robert Avatar answered Oct 19 '22 07:10

Robert