SQL 2000 Find and Replace
I needed to find and replace text in a text field in sql2000… here’s how I got it right:
SET @StringToReplace = ‘baad string’
declare @NewString varchar(1000)
SET @NewString = ‘new improved string’
declare @start int
declare @end int
SELECT @end = len(@StringToReplace)-2
declare @currentrecord int
declare @ptrval BINARY(16)
declare @TotalOldTextInstancesStillToBeFixed int
SELECT @TotalOldTextInstancesStillToBeFixed = count(*) FROM tblTable WHERE body LIKE @StringToReplace
while (@TotalOldTextInstancesStillToBeFixed > 0)
begin
SELECT top 1 @currentrecord = TableID FROM tblTable WHERE body LIKE @StringToReplace ORDER BY TableID
–select @currentrecord
SELECT @ptrval = textptr(tblTable.body),@start = (PATINDEX(@StringToReplace, body)-1)
FROM tblTable WHERE tblTable.TableID = @currentrecord
–select @start,@end
updatetext tblTable.body @ptrval @start @end @NewString
SELECT @TotalOldTextInstancesStillToBeFixed = count(*) FROM tblTable WHERE body LIKE @StringToReplace
end
Disclaimer: test this thoroughly in a dev environment before letting it loose on your production data. Seriously.
Developer by day, husband and dad by night and dreaming about sport inbetween.