Saturday, January 7, 2017

Replace a specific word in a column in all rows

In this sample I am searching for all rows beginning with the name 'RED' for the DepartmentName column. Then replace the value 'RED' with 'BLUE'. For an instance such a change might come in handy in a scenario when the company is re-branding :)

(i)

UPDATE tbl_Department
SET DepartmentName = REPLACE(DepartmentName, 'RED', 'BLUE')
WHERE DepartmentName LIKE ('RED%')


If the column containing the content (In this example: DepartmentName) is of 'Text' you might get an error as:
"Argument data type text is invalid for argument 1 of replace function"

In such scenarios the column has to be casted. So the changes in the update would look like:

(ii)

UPDATE tbl_Department
SET DepartmentName = REPLACE(CAST(DepartmentName AS NVARCHAR(MAX)), 'RED', 'BLUE')
WHERE DepartmentName LIKE ('RED%')


No comments:

Post a Comment