How to make a list of T-SQL results with comma's between them?

拈花ヽ惹草 提交于 2019-11-29 01:58:10

this will give you the list of values in a comma separated list

create table #temp
(
    y int,
    x varchar(10)
)

insert into #temp values (1, 'value 1')
insert into #temp values (1, 'value 2')
insert into #temp values (1, 'value 3')
insert into #temp values (1, 'value 4')

DECLARE @listStr varchar(255)

SELECT @listStr = COALESCE(@listStr+', ', '') + x
FROM #temp
WHERE #temp.y = 1

SELECT @listStr as List

drop table #temp

You can use XML to do that:

DECLARE @V VarChar(4000);

SELECT @V = CONVERT(VarChar(4000), (
  SELECT x + ', '
  FROM t
  WHERE t.y = z
  FOR XML PATH('')
));
-- To remove the final , in the list:
SELECT @V = LEFT(@V, LEN(@V) - 2);

SELECT @V;

For other options check out Concatenating Row Values in SQL.

Since it's SQL Server 2008, you can use FOR XML:

SELECT SUBSTRING(
    (SELECT ',' + t.x
     FROM t
     WHERE t.y = z
     FOR XML PATH('')),
    2,
    200000) AS CSV

FOR XML PATH('') selects the table as XML, but with a blank path. The SUBSTRING(select, 2, 2000000) removes the leading ', '

Justin Pihony

You could use a recursive CTE for this:

CREATE TABLE #TableWithId (Id INT IDENTITY(1,1), x VARCHAR)

INSERT INTO #TableWithId
SELECT x 
FROM t
WHERE t.y = z

WITH Commas(ID, Flattened)
AS
(
-- Anchor member definition
    SELECT ID, x AS Flattened
    FROM #TableWithId
    WHERE ID = 1
    UNION ALL
-- Recursive member definition
    SELECT #TableWithId.Id, Flattened + ',' + x
    FROM #TableWithId
    INNER JOIN Commas
        ON #TableWithId.Id + 1 = Commas.Id
)
-- Statement that executes the CTE 
SELECT TOP 1 Flattened
FROM Commas
ORDER BY id;
GO
larryr

How about something like this???

DECLARE @x AS VARCHAR(2000)
SET @x = ''
SELECT @x = @x + RTRIM(x) + ','
FROM t
SELECT @x = SUBSTRING(@x, 1, LEN(@x) - 1)
PRINT @x
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!