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

僤鯓⒐⒋嵵緔 提交于 2019-12-29 05:20:08

问题


Suppose we have a simple query like this:

SELECT x 
FROM t
WHERE t.y = z

If we have one record in the result set, I want to set variable @v to that one value. If we have two or more records, I'd like the results to be separated by a comma and a space. What is the best way to write this T-SQL code?

Example:

result set of 1 record:

Value1

result set of 2 records:

Value1, Value2

result set of 3 records:

Value1, Value2, Value3

回答1:


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



回答2:


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.




回答3:


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 ', '




回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/9726660/how-to-make-a-list-of-t-sql-results-with-commas-between-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!