SQL Server选择结果集值为逗号分隔的字符串

时间:2014-06-04 08:35:12

标签: sql sql-server

我在存储过程中有以下查询。

set @result1='EmpId,EmpName,Phone,City'

set @result2='select '+ @result1+ ' from [emptable]'+' where EmpId=1 and
EmpjoinDate= ''May-2014'''

exec(@result2)

查询返回

EmpId | EmpName | Phone  | City
----------------------------------   
  1   | John    | 832942 | NewYork

现在如何添加查询以便存储过程返回单列结果

| EmpInfo .........................|
------------------------------------    
1,John,832942,NewYork

请回复。感谢。

5 个答案:

答案 0 :(得分:2)

set @result1='CONCAT(EmpId,',',EmpName,',',Phone,',',City)'

set @result2='select '+ @result1+ ' as EmpInfo from [emptable]'+' where EmpId=1 and
EmpjoinDate= ''May-2014'''

exec(@result2)

答案 1 :(得分:0)

如果我清楚地告诉你,那么这就是你想要的人。 您必须使用逗号连接字段

set @result1='EmpId+'',''+EmpName''+'',''+''Phone''+'',''+''City'

set @result2='select '+@result1+' as EmpInfo from [emptable]'+' where EmpId=1 and
EmpjoinDate= ''May-2014'''

exec(@result2)

答案 2 :(得分:0)

您必须在@ result1变量中构建字符串:

set @result1='EmpId+'',''+EmpName+'',''+Phone+'',''+City'

在Management Studio中,您还可以转到“查询菜单”并选择“结果到” - > “结果到文本”如果这对你来说已经足够了。

答案 3 :(得分:0)

您可以做的是,在收到@result1后,您可以按照自己的意愿替换数据:

set @result1='EmpId,EmpName,Phone,City'


SET  @result1  = REPLACE (@result1, ',', ' + '','' + ')

--SET  @result1  = 'CONCAT ( ' + REPLACE (@result1, ',', ' , '','' , ') + ')'   -- OR THIS IF you have INT inside this columns


set @result2='select '+ @result1+ ' from [emptable]'+' where EmpId=1 and
EmpjoinDate= ''May-2014'''

exec(@result2)

CONCAT函数看起来更好,如果你有Server 2012.如果没有,你需要CAST INT值到String

答案 4 :(得分:0)

使用For XMLSTUFF将查询重写为:

declare @result1 varchar(max), 
        @result2 varchar(max) 
--Modify all input columns using Cast function to cast int datatype columns 
--to varchar .Also this way you can add as many columns from table 'emptable'
--as you want

set @result1=''','' + cast(EmpId as varchar(20)) + '','' + EmpName + '','' 
    + cast(Phone as varchar(20)) + '','' + City'

set @result2='select STUFF((SELECT '+ @result1+ '  from [emptable] 
    '+' where EmpId=1 FOR XML PATH('''')), 1, 1, '''') as  EmpInfo'

exec(@result2)

点击此处Demo

相关问题