简体   繁体   English

如何编写sql从多个行转换一个字符串?

[英]How to write sql to convert one string from mutiple rows?

Supose I have a table with following kind of data: 假设我有一个包含以下类型数据的表:

Tab(id, myString)
1  A
2  B
3  C
...

I want to a SQL can return all one string for all values in Column myString. 我想让SQL可以为myString列中的所有值返回所有一个字符串。 So the result I want looks like: "A, B, C" 所以我想要的结果看起来像:“ A,B,C”

If I don't want to use cursor and stored procedure, is it possible sql to get such kind of result? 如果我不想使用游标和存储过程,sql是否有可能获得这种结果?

Use T-SQL row concatenation: 使用T-SQL行串联:

declare @s varchar(max)
set @s = ''
select @s = @s +
 case when @s = '' then '' else ', ' end + Letter
from MyTable

select @s

edited removed trailing ", " 编辑删除的尾随“,”

A combination of using FOR XML PATH (providing an empty element name) and STUFF is a common SQL Server (2005+) technique. 结合使用FOR XML PATH (提供一个空元素名称)和STUFF是一种常见的SQL Server(2005+)技术。 It doesn't require declaration of any local variables and can therefore be run outside of batch or procedure. 它不需要声明任何局部变量,因此可以在批处理或过程之外运行。

SELECT STUFF(
(SELECT ',' + t.myString
FROM TAB t
ORDER BY t.Id
FOR XML PATH('')),1,1,'') AS CSV
Declare @tbl table(ID nvarchar(1),[myString] nvarchar(100))
Insert into @tbl values(1,'A'); 
Insert into @tbl values(2,'B'); 
Insert into @tbl values(3,'C'); 
DECLARE @CSVList varchar(100)

SELECT @CSVList = COALESCE(@CSVList + ' , ', '') + 
   [myString]
FROM @tbl


SELECT @CSVList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM