Author Topic: T-SQL code to concatenate all the values of a column into one row  (Read 5420 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
T-SQL code to concatenate all the values of a column into one row 

This trick uses a variable in the SELECT statement and appends all the values of a given column to that variable.
Code: [Select]
USE pubs
GO
DECLARE @title_ids varchar(150), @delimiter char
SET @delimiter = ','
SELECT @title_ids = COALESCE(@title_ids + @delimiter, '') + title_id FROM titles
SELECT @title_ids AS [List of Title IDs]

NOTE:      A limitation to be aware of is that varchar can go upto a max size of
      8000 characters. If your data occupies more space, the output will be
      truncated.