I have a string in my stored proc like \',,,sam,,bob,\'
or \',,,\'
from the above string I have to delete multiple commas from it, it must look like
<
Your solutions are good but
so i wrote based on Marcin solution set-based universal code for replacement of every declared kind of duplicates:
DECLARE @Duplicate NVARCHAR(100)= '#$'
DECLARE @TestString NVARCHAR(MAX)= 'test_test__f##f2$$g'
DECLARE @Replacement NVARCHAR(MAX)= ''
DECLARE @OutputString NVARCHAR(MAX)= @teststring ;
WITH numbers
AS ( SELECT ROW_NUMBER() OVER ( ORDER BY o.object_id, o2.object_id ) Number
FROM sys.objects o
CROSS JOIN sys.objects o2
),
chars
AS ( SELECT SUBSTRING(@Duplicate, 1, 1) CHAR ,
CAST(1 AS INT) [LEVEL]
UNION ALL
SELECT SUBSTRING(@Duplicate, numbers.Number, 1) CHAR ,
CAST(numbers.Number AS INT) [LEVEL]
FROM numbers
JOIN chars ON chars.Level + 1 = numbers.Number
WHERE LEN(SUBSTRING(@Duplicate, numbers.Number, 1)) > 0
),
Replicated
AS ( SELECT REPLICATE(CHAR, numbers.number) Repl ,
numbers.Number
FROM chars
CROSS JOIN numbers
)
SELECT @OutputString = REPLACE(@OutputString, Repl, @Replacement)
FROM replicated
WHERE number <= LEN(@TestString)
SELECT @OutputString
You can declare every kind of char in Duplicate string and every replacement string in @Replacement. Additional gain IMHO is that i search for replacement only in range of maximum length of input string