在 SQL Server < 2017 的版本上,您必须使用STUFF
和FOR 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
);