One way (prior to SQL 2012) is to use a variable to concatenate the row results as follows:
DECLARE @texto varchar(max);
SELECT @texto = ISNULL(@texto + ', ', '') + cli.nome
FROM cliente cli;
print @texto;
Where the ISNULL
ensures that the comma will only be inserted if there is previous value assigned to the variable (in case starting to place the comma only after the José
).
Another way is to use the syntax FOR XML PATH('')
:
SELECT DISTINCT SUBSTRING((SELECT ',' + cli.nome AS [text()]
FROM cliente cli
FOR XML PATH ('')), 2, 8000) AS texto
FROM cliente cli2
From the version 2017
of SQL Server
you can use the function STRING_AGG
:
SELECT STRING_AGG(cli.nome, ',') AS texto
FROM cliente cli;
STRING_AGG
Concatenate the values of the string expressions and place the separator values between them. Separator is not added at the end of the string.
References: