我有一个select
返回一列的查询,我想将其转换为用“,”分隔的字符串行
Select name
from tblUsers
给出一个结果:
Row1; asieh
Row2:amir
Row3:safoora
我想回来
Row1: asieh,amir,safoora
我有一个select
返回一列的查询,我想将其转换为用“,”分隔的字符串行
Select name
from tblUsers
给出一个结果:
Row1; asieh
Row2:amir
Row3:safoora
我想回来
Row1: asieh,amir,safoora
MS SQL Server 2008 架构设置:
CREATE TABLE tblUsers
([name] varchar(7))
;
INSERT INTO tblUsers
([name])
VALUES
('asieh'),
('amir'),
('safoora')
;
查询 1:
SELECT STUFF((
select ','+ name
from tblUsers
FOR XML PATH('')
)
,1,1,'') AS names
结果:
| NAMES |
|--------------------|
| asieh,amir,safoora |
这是使用变量的解决方案:
DECLARE @out VARCHAR(MAX)
SELECT @out = COALESCE(@out+',' ,'') + name
FROM tblUsers
SELECT @lout
尝试这个 :
Create Table #tblUsers ( Name Varchar(100) );
Insert Into #tblUsers Values ('Row1; asieh'),('Row2:amir'),('Row3:safoora')
Select Stuff((Select ',' + Name
From #tblUsers
For Xml Path('')
), 1, 1, '' ) As ConcatenedString
drop table #tblUsers