Skip to content

VARYING

DECLARE @id TABLE (Id INT)
INSERT INTO @id VALUES(1),(2),(3)
DECLARE @value varchar(MAX)
SELECT @value = COALESCE(@value + ', ', '') + CAST(Id as varchar)
FROM @id
SELECT @value as Ids
Ids
----
1, 2, 3

In the example, a temporary table is declared and populated with values. A variable @value of type varchar(MAX) is used to concatenate the values in the column ‘Id’ of the @id table. The COALESCE function ensures an empty string is used instead of NULL for the first item in the list, and CAST is used to convert the integer value to a varchar type for string concatenation. The final SELECT statement displays the concatenated Ids.