0

我有以下查询:

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

感谢您的回复

4

2 回答 2

2

在 SQL Server < 2017 的版本上,您必须使用STUFFFOR XML PATH子查询。

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(''), 
TYPE).value(N'./text()[1]', N'varchar(max)'), 1, 2, '');

在 2017+ 年,您绝对应该切换到STRING_AGG()

SELECT STRING_AGG(CONCAT(c.ChallanNo, '-',
    CONVERT(char(11), c.ChallanDate, 106)), ', ')
  FROM dbo.Challan AS c
  WHERE EXISTS 
  (
    SELECT 1 FROM dbo.ChallanDetail AS cd
    WHERE cd.ChallanID = c.ChallanID
    AND cd.PTUID = 42192
  );
于 2012-06-07T06:20:33.277 回答
1
declare @result varchar(max) = ''

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

-- remove trailing ,
select left(@result, len(@result) - 1)
于 2012-06-07T06:06:28.657 回答