SQL Server: Replace specific char one by one in a string

This Stored Procedure replaces specific character to a given string. Note that
CREATE PROCEDURE spReplaceOneByOneChar(@str as varchar(100),@toreplace char(1))
As

DECLARE @i int
DECLARE @res as varchar(100)

set @i= 1

WHILE @i<=Len(@str)
BEGIN

SET @res = STUFF(@str, @i,1,@toreplace)

PRINT @res
SET @i=@i+1

END

Usage of SP and results depicted below
spReplaceOneByOneChar '1234','x'



If you need to have the values resultset in a table you can use below SP
CREATE PROCEDURE spReplaceOneByOneChar(@str as VARCHAR(100),@toreplace VARCHAR(10))
AS
BEGIN
DECLARE @i int
DECLARE @res as varchar(100)
DECLARE @tmptable as table(resultset varchar(100))

SET @i= 1

WHILE @i<=Len(@str)
BEGIN

INSERT INTO @tmptable (resultset)
SELECT STUFF(@str, @i,1,@toreplace)

SET @i=@i+1;
END

SELECT * from @tmptable
END


No comments:

Post a Comment