Essentially, I'm trying to loop through the contents of @sprocs
variable, implement the replace function, and print the respective changes. When I execute the code, the @spname
variable is printed off, just not with the expected result.
declare @sprocs cursor
declare @spname nvarchar(max)
set @sprocs = cursor for
select ROUTINE_DEFINITION
from INFORMATION_SCHEMA.ROUTINES
where ROUTINE_TYPE = 'Procedure' AND
ROUTINE_DEFINITION like '%someString%'
open @sprocs
fetch next from @sprocs into @spname
while @@FETCH_STATUS = 0
Begin
set @spname = replace(@spname, '%someString%', 'Hello')
print @spname
fetch next from @sprocs into @spname
end
Expected result would look like this:
Before
Lorem ipsum dolor sit amet, someString adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco someString nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. someString sint occaecat cupidatat non someString, sunt in culpa qui officia deserunt mollit anim id est laborum.
After
Lorem ipsum dolor sit amet, Hello adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco Hello nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Hello sint occaecat cupidatat non Hello, sunt in culpa qui officia deserunt mollit anim id est laborum.
I thought - initially - that is might be an issue with @spname
variable type, but since it's declared as an nvarchar(max)
, I can't see that being the issue.
What's preventing the expected print out?
replace(@spname, 'someString', 'Hello')
instead ofreplace(@spname, '%someString%', 'Hello')
.. the string to be replaced should be declared literally .. wildcards don't work here. – Vamsi Prabhala%a
would mean ends with "a", while%a%
means *"a" is somewhere in the middle anda%
means "starts with "a". AREPLACE
will find and replace the given string wherever it is located - even several times. If you'd know that the string to change is at the beginning or at the end, you'd probably useLEFT
orSUBSTRING
to cut this part off and concatenate the rest with your new string. – Shnugo