I am seeing some strange behaviour when combining while loops with assignments in SQL Server. I have the following SQL Server TSQL code:
DECLARE @string nvarchar(max) = 'Foo bar bat.';
WHILE PATINDEX('bar', @string) != 0
BEGIN
SET @string = REPLACE(@string, 'bar', '')
END
SELECT @string
I would expect the result here to be Foo bat., but the result is actually Foo bar bat., as if the original @string variable was unchanged. It doesn't get into an infinite loop though, which suggests that the value of @string did get updated in the way I wanted, but for some reason this gets forgotten when we break out of the while loop.
What exactly is causing this to happen, and how can I achieve the expected result?
I am running SQL Server 2016 SP2.
_a_in this example, that would match both 'bar' and 'bat'), find the first substring matching the pattern (e.g. 'bar'), do some processing and then REPLACE the exact substring out of the string, so that on the next iteration the 2nd substring matching the pattern (e.g. 'bat') gets matched and I can process that. Sorry that wasn't clear, I reduced the code down to a minimal example that gave the same error but maybe I should have left more of that logic in.