What I need is to search for a string in a specific column (datatype: text
) of a table and replace it with another text.
For example
Id | Text
-----------------------------
1 this is test
2 that is testosterone
If I chose to replace test with quiz, results should be
this is quiz
that is quizosterone
What I've tried so far?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROC [dbo].[SearchAndReplace]
(
@FindString NVARCHAR(100)
,@ReplaceString NVARCHAR(100)
)
AS
BEGIN
SET NOCOUNT ON
SELECT CONTENT_ID as id, CONTENT_TEXT, textptr(CONTENT_TEXT) as ptr, datalength(CONTENT_TEXT) as lng
INTO #newtable6 FROM HTML_CONTENTS
DECLARE @COUNTER INT = 0
DECLARE @TextPointer VARBINARY(16)
DECLARE @DeleteLength INT
DECLARE @OffSet INT
SELECT @TextPointer = TEXTPTR(CONTENT_TEXT)
FROM #newtable6
SET @DeleteLength = LEN(@FindString)
SET @OffSet = 0
SET @FindString = '%' + @FindString + '%'
WHILE (SELECT COUNT(*)
FROM #newtable6
WHERE PATINDEX(@FindString, CONTENT_TEXT) <> 0) > 0
BEGIN
SELECT @OffSet = PATINDEX(@FindString, CONTENT_TEXT) - 1
FROM #newtable6
WHERE PATINDEX(@FindString, CONTENT_TEXT) <> 0
UPDATETEXT #newtable6.CONTENT_TEXT
@TextPointer
@OffSet
@DeleteLength
@ReplaceString
SET @COUNTER = @COUNTER + 1
END
select @COUNTER,* from #newtable6
drop table #newtable6
SET NOCOUNT OFF
I get the error:
Msg 7116, Level 16, State 4, Procedure SearchAndReplace, Line 31
Offset 1900 is not in the range of available LOB data.
The statement has been terminated.
Thank you