Using patindex in a loop seemed the best way forward to deal with the multiple replacements and the numbers and underscore characters. The other problem was that I had to step through the original text to do the replacements so that if a text was replaced with the same text then the function wouldn't get stuck. I achieved this by using sub string to get the remaining text after each replacement.
@OrigString varchar(8000),
@LookFor varchar(1000),
@ReplaceWith varchar(1000))
returns varchar(8000)
BEGIN
DECLARE @findIndex int
DECLARE @lengthLookFor int
DECLARE @lengthReplace int
DECLARE @totalLength int
DECLARE @tempString as varchar(8000)
DECLARE @counter int
SET @OrigString = '(' + @OrigString + ')'
SET @lengthLookFor = LEN(@LookFor)
SET @lengthReplace = LEN(@ReplaceWith)
SET @totalLength = LEN(@OrigString)
SET @tempString = @OrigString
SET @counter = 0
DECLARE @stuffindex int
SET @stuffindex = 0
DECLARE @substring int
SET @substring = 0
WHILE PATINDEX('%' + @LookFor +'[^a-z0-9]%', @tempString) != 0
BEGIN
SET @findIndex = PATINDEX('%[^a-z0-9]' + @LookFor +'[^a-z0-9]%', @tempString) + 1
--SELECT @findIndex as 'findIndex'
set @stuffindex = @findIndex + @substring
if(@counter >0)
set @stuffindex = @stuffindex - 1
--SELECT @stuffindex as stuffindex
SET @OrigString = STUFF(@OrigString, @stuffindex , @lengthLookFor, @ReplaceWith)
--SELECT @OrigString as 'outputstring'
SET @substring = @stuffindex + @lengthReplace
--SELECT @substring as substring
SET @tempString = SUBSTRING(@OrigString,@substring,@totalLength - @findIndex)
--SELECT @tempString as 'tempstring'
SET @counter = @counter + 1
END
SET @OrigString = SUBSTRING( @OrigString, 2, LEN(@OrigString)- 2)
No comments:
Post a Comment