如何将多行组合到SQL Server 2005中以逗号分隔的列表中?
现在,我有一个这样的SQL查询:
SELECT X, Y FROM POINTS
它返回如下结果:
XY ---------- 12 3 15 2 18 12 20 29
我想要返回结果全部在一行中,像这样(适合在HTML <AREA>标签中使用):
XYLIST ---------- 12,3,15,2,18,12,20,29
有没有办法使用SQL来做到这一点?
DECLARE @XYList varchar(MAX) SET @XYList = '' SELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ',' FROM POINTS -- Remove last comma SELECT LEFT(@XYList, LEN(@XYList) - 1)
感谢您的快速和有益的答案家伙!
我刚刚发现了另一个快速的方法来做到这一点:
SELECT STUFF(( SELECT ',' + X + ',' + Y FROM Points FOR XML PATH('') ), 1, 1, '') AS XYList
信贷给这个家伙:
使用COALESCE
技巧,你不必担心后面的逗号:
DECLARE @XYList AS varchar(MAX) -- Leave as NULL SELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) FROM POINTS
DECLARE @s VarChar(8000) SET @s = '' SELECT @s = @s + ',' + CAST(X AS VarChar) + ',' + CAST(Y AS VarChar) FROM POINTS SELECT @s
只要摆脱领先的逗号