Sekhar
Sekhar

Reputation: 5797

T-SQL string replace in Update

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.

Upvotes: 93

Views: 112575

Answers (3)

Kofi Sarfo
Kofi Sarfo

Reputation: 3360

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')

Upvotes: 170

Tawani
Tawani

Reputation: 11198

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

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

Upvotes: 13

Joe Stefanelli
Joe Stefanelli

Reputation: 135848

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

Upvotes: 6

Related Questions