Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save brunotdantas/26b584ea9887223b241effcde83d75f7 to your computer and use it in GitHub Desktop.
Save brunotdantas/26b584ea9887223b241effcde83d75f7 to your computer and use it in GitHub Desktop.
Simple function to recursively replace a pattern in a string.
CREATE FUNCTION dbo.RepetitiveReplace_fn
(
@P_String VARCHAR(MAX),
@P_Pattern VARCHAR(MAX),
@P_ReplaceString VARCHAR(MAX),
@P_ReplaceLength INT = 1
)
RETURNS VARCHAR(MAX)
BEGIN
DECLARE @Index INT;
-- Get starting point of pattern
set @Index = patindex(@P_Pattern, @P_String);
while @Index > 0
begin
--replace matching charactger at index
set @P_String = stuff(@P_String, patindex(@P_Pattern, @P_String), @P_ReplaceLength, @P_ReplaceString);
set @Index = patindex(@P_Pattern, @P_String);
end;
return @P_String;
END;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment