Blog Post

T-SQL – Query to get Distinct,Sorted, Comma Separated values in to a variable

,

CREATE  TABLE  #temp(name char(3))
INSERT INTO #temp VALUES ('CD')
,('AB')
,('LM')
,('BC')
,('GH')
,('KJ')
,('AB')
DECLARE @cols AS NVARCHAR(MAX);
SELECT @COLS =  substring(list, 1, len(list) - 1)
FROM   (SELECT list = 
          (SELECT DISTINCT name + ','
           FROM  #temp
           ORDER BY name + ','
         FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)')) AS T
SELECT @COLS
DROP TABLE #temp

CSV_Values

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating