SQL Server – Create and Parse Comma Seperated List

XML Approach:
Reads : 2 Duration:5 ms

Substring Approach:
Reads : 16 Duration: 14 ms

--declare a variable and populate it with a comma separated string
DECLARE @SQLString VARCHAR(MAX)
SET @SQLString = N'94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111'

--append a comma to the string to get correct results with empty strings or strings with a single value (no commas)
SET @SQLString = @SQLString + ',';

DECLARE @X XML
SET @X = CAST('' + REPLACE(@SQLString, ',', '') + '' AS XML)

SELECT t.value('.', 'INT')
FROM @x.nodes('/A') as x(t)


declare @itemids VARCHAR(MAX)
SET @itemids=N'94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111'

DECLARE @Delimiter NCHAR(2)
SELECT @Delimiter = ','
SELECT
LTRIM(RTRIM(SUBSTRING(@itemids, [Number],CHARINDEX(@Delimiter, @itemids + @Delimiter, [Number]) - [Number])))
FROM
dbo.helper_Number (NOLOCK)
WHERE
Number <= LEN(@itemids)
AND SUBSTRING
(
@Delimiter + @itemids, [Number], LEN(@Delimiter)
) = @Delimiter

 Quick Way to Create Comma Seperated List using STUFF and XML PATH

-- STUFF SYNTAX
-- STUFF ( character_expression , start , length , replaceWith_expression )

SELECT  STUFF(( SELECT  DISTINCT
                        ',' + CONVERT(VARCHAR(255), ItemID)
                FROM    xib.Item
              FOR
                XML PATH('')
              ), 1, 1, '')

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *