T-SQL string replace in Update

StringTsqlReplace

String Problem Overview


I need to update the values of a column, with a substring replace being done on the existing values.

Example:

Data contains abc@domain1, pqr@domain2 etc.

I need to update the values such that @domain2 is replaced with @domain1.

String Solutions


Solution 1 - String

The syntax for REPLACE:

REPLACE (string_expression,string_pattern,string_replacement)

So that the SQL you need should be:

UPDATE [DataTable] SET [ColumnValue] = REPLACE([ColumnValue], 'domain2', 'domain1')

Solution 2 - String

If anyone cares, for NTEXT, use the following format:

SELECT CAST(REPLACE(CAST([ColumnValue] AS NVARCHAR(MAX)),'find','replace') AS NTEXT) 
    FROM [DataTable]

Solution 3 - String

update YourTable
    set YourColumn = replace(YourColumn, '@domain2', '@domain1')
    where charindex('@domain2', YourColumn) <> 0

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
QuestionSekharView Question on Stackoverflow
Solution 1 - StringKofi SarfoView Answer on Stackoverflow
Solution 2 - StringTawaniView Answer on Stackoverflow
Solution 3 - StringJoe StefanelliView Answer on Stackoverflow