简体   繁体   中英

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. So the result I want looks like: "A, B, C"

If I don't want to use cursor and stored procedure, is it possible sql to get such kind of result?

Use T-SQL row concatenation:

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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