如何将多行中的数据合并到SQL Server中的一行?

时间:2015-10-28 04:15:31

标签: sql-server sql-server-2008 tsql

我想使用FOR XML PATH将多行中的数据合并到SQL Server中的一行,但同样它不起作用。我试试

enter image description here

foo()

结果相同

SELECT STUFF((SELECT ',' + ZZ.UNAME FROM X XX 
    INNER JOIN Y YY ON YY.UUID = XX.UUID
    INNER JOIN Z ZZ ON ZZ.UID = YY.UID
    WHERE XX.TID = 'T1'
    FOR XML PATH('')),1,1,'') AS [MERGE_NAME]

你能告诉我一些错误或错误吗?谢谢

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

DECLARE @merge_name VARCHAR(1000) = ''
SELECT @merge_name = @merge_name + ',' + ZZ.UNAME FROM X XX 
                                    INNER JOIN Y YY ON YY.UUID = XX.UUID
                                    INNER JOIN Z ZZ ON ZZ.UID = YY.UID
                                    WHERE XX.TID = 'T1'
SELECT RIGHT(@merge_name, LEN(@merge_name)-1)

如果您使用STUFF,可以尝试:

SELECT REPLACE(REPLACE(STUFF((SELECT ZZ.UNAME
                              FROM X XX 
                                 INNER JOIN Y YY ON YY.UUID = XX.UUID
                                 INNER JOIN Z ZZ ON ZZ.UID = YY.UID
                              WHERE XX.TID = 'T1' FOR XML PATH('')),1,0,''), '<Name>', ''), '</Name>', ',')