在sql server中将一列中的多行数据合并到一行中

在sql server中将一列中的多行数据合并到一行中,sql,sql-server,sql-server-2008,tsql,Sql,Sql Server,Sql Server 2008,Tsql,我有一张像这样的桌子 create table temp_table (col1 int) insert into temp_table values(1), (2), (3), (4) 我在这张表中有一些数据,比如 create table temp_table (col1 int) insert into temp_table values(1), (2), (3), (4) 现在我希望数据输出如下: 1,2,3,4 我使用了以下查询: select cast(col1 as

我有一张像这样的桌子

create table temp_table (col1 int)
insert into temp_table 
values(1), (2), (3), (4)
我在这张表中有一些数据,比如

create table temp_table (col1 int)
insert into temp_table 
values(1), (2), (3), (4)
现在我希望数据输出如下:

1,2,3,4
我使用了以下查询:

select cast(col1 as nvarchar)+',' 
from temp_table 
for xml path('')
问题是输出是XML格式的,我需要简单的文本/字符串格式。我尝试搜索转置,但到处都提到XML,这对我没有帮助


有什么建议吗?

如果您在给定的链接中确实没有得到建议:

declare @temp nvarchar(max)
select @temp = COALESCE(@temp + ', ', '') + CAST(col1 as nvarchar) from temp_table
select @temp
select STUFF((
          SELECT ',' + cast(col1 as nvarchar)
          FROM temp_table
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
请尝试此查询

Select STUFF((SELECT ',' + Cast(col1 As nvarchar) FROM temp_table 
          FOR XML PATH('')), 1, 1, '') As MyColumn

看看这里:您需要东西和XML_路径,比如:@Raphaël Althaus yups!!,请参阅更新的。。。