Create varchar from SELECT result

13,603

Solution 1

DECLARE @result varchar(MAX)
SET @result = '';

SELECT 
  @result = @result + NAME + ','
FROM
  Table
WHERE
  ID = @Id

SET @result = SUBSTRING(@result, 1, LEN(@result) - 1)

SELECT @result

Enjoy :D

Solution 2

DECLARE @CSV varchar(max)

SET @CSV = ''

SELECT @CSV = @CSV + Col1 + ',' FROM Table WHERE ...

SET @CSV = LEFT(@CSV, LEN(@CSV) -1)

PRINT @CSV
Share:
13,603
Sergey Metlov
Author by

Sergey Metlov

Xamarin software architect. Careers profile.

Updated on June 27, 2022

Comments

  • Sergey Metlov
    Sergey Metlov almost 2 years
    DECLARE @result varchar(MAX)
    
    SELECT 
      NAME
    FROM
      Table
    WHERE
      ID = @Id
    

    I need to fill @result with result Names, separated by ','.
    For example, if SELECT returns 'A','B' and 'C', the @result should be 'A, B, C'.
    It is Microsoft SQL Server 2008.