Replace function in TEXT or NTEXT fields SQL Server
We often use replace function in SQL server databases to find and replace a specific string. The SQL statement is straightforward and there is no any issue when we search and replace a string on a column with a datatype, not either TEXT or NTEXT.
The general search and replace SQL statement is
UPDATE tbl_name
SET column_name = REPLACE(column_name, 'old_string', 'new_string')
WHERE column_name like '%old_string%'
The problem occurs when you try to search and replace a string on a column with datatype TEXT or NTEXT and the error message: Argument data type text is invalid for argument 1 of replace function. and SQL server do not have any recommendation on how to resolve, probably we know REPLACE function only work on varchar or nvarchar datatype
The simplest way is converted TEXT or NTEXT data to NVARCHAR(MAX) and then use Replace function. Using below query you can replace string in TEXT or NTEXT data type column.
UPDATE tbl_name
SET column_name =
CAST(REPLACE(CAST(column_name as nvarchar(MAX)),'old_string','new_string') AS NText)
WHERE column_name LIKE '%old_string%
This way you can replace strings in TEXT or NTEXT column.