Last active
December 1, 2022 20:10
-
-
Save jkdba/ca13fe8f2a9855c4bdbfd0a5d3dfcda2 to your computer and use it in GitHub Desktop.
Simple function to recursively replace a pattern in a string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
recursive function does not make since here if there is more than 32 indices to replace due to sql recursive/nested trigger limit.