Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a part of the string using replace function in tsql?

Hi I have a column of nvarchar(1000) type. I need to get rid of encode characters from that column and replace them with their special characters. For Example:

column value is : 'This text values contains this '&' this'.

I have to replace '&' with '&'.

  1. First have to find the record which has '&' in the column (may be using like condition)
  2. And then replace only this word with its special character

How do i do that? Pl. help

like image 357
User13839404 Avatar asked Jan 31 '11 21:01

User13839404


People also ask

How can I replace part of a string in SQL?

SQL Server REPLACE() Function The REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive.

Can we use Replace with update in SQL?

You can use REPLACE in an UPDATE statement.

How do you update part of a field in SQL?

If you'd like to replace a substring with another string, simply use the REPLACE function. This function takes three arguments: The string to change (which in our case was a column). The substring to replace.


2 Answers

This will replace in the entire column

REPLACE(MyColumn, '&', '&')

You'll have to nest other replacements...

REPLACE(REPLACE(MyColumn, '&', '&'), '>', '>')

All together

UPDATE myTable
SET MyColumn = REPLACE(MyColumn, '&', '&')
WHERE MyColumn LIKE '%&%'
like image 158
gbn Avatar answered Oct 26 '22 01:10

gbn


UPDATE mytable
    SET mycol = REPLACE(mycol, N'&', N'&')
    WHERE mycol LIKE '%&%'

EDIT If you decide to replace multiple html entities in one go, the order of the replacements may change results.

For example:

<

becomes &< if you replace first &amp; with & and then &lt; with <, but the result will be &lt; if you first try to replace &lt; with < and then &amp; with &.

If I have to do that kind of replacement, I usually replace &amp; last for this reason. Sure, an edge case, and not something which happens often, but you never know...

like image 24
marapet Avatar answered Oct 26 '22 02:10

marapet