A personal repository of technical notes. - CSC

SQL Concatenate Row Data into Variable

Problem

Need to generate a comma-delimited string list from data contained in rows of table

Solution

DECLARE @commaDelimitedList varchar(8000)
SET @commaDelimitedList = '' -- Must set to empty value

SELECT @commaDelimitedList = @commaDelimitedList + [MyColumn] + ','
FROM [MyTable]

-- Remove trailing comma from list
IF (@commaDelimitedList <> '')
BEGIN
      SET @commaDelimitedList = LEFT(@commaDelimitedList, LEN(@commaDelimitedList) - 1)
END

-- Return record set
SELECT @commaDelimitedList AS 'CommaDelimitedList'

No comments:

Post a Comment