从SQL Query生成字符串

时间:2012-06-07 05:59:52

标签: sql-server

我有以下查询:

SELECT ChallanNo+'-'+CONVERT(VARCHAR(12),ChallanDate,106) 
   FROM Challan WHERE ChallanID IN 
   (SELECT ChallanID FROM ChallanDetail WHERE PTUID=42192)

此查询结果将为:

151468-29 May 2012
151591-31 May 2012

现在我需要一个这样的字符串:

151468-29 May 2012, 151591-31 May 2012

感谢您的回复

2 个答案:

答案 0 :(得分:2)

SELECT STUFF((SELECT ', ' + CONVERT(VARCHAR(32), ChallanNo) 
  + '-' + CONVERT(CHAR(11), ChallanDate, 106)  
  FROM dbo.Challan WHERE ChallanID IN 
   (SELECT ChallanID FROM dbo.ChallanDetail WHERE PTUID = 42192)
FOR XML PATH('')), 1, 2, '');

答案 1 :(得分:1)

declare @result varchar(max) = ''

select @result = @result + ChallanNo + '-' + 
                 CONVERT(VARCHAR(12),ChallanDate,106) + ','
from ...

-- remove trailing ,
select left(@result, len(@result) - 1)