Andy's blog

If you always do what you've always done, you'll always get what you've always got.

0%

2020-12-07-SQL SERVER FOR XML PATH語法介紹

工作上最近一直遇到將不同 ROW的抹個欄位值合併起來,記錄一下


參考資料:
[食譜好菜] SQL Server 使用「FOR XML」語法做欄位合併


情境:
今天我需要將不同 ROW的抹個欄位值合併起來,改如何做呢?

1
2
3
4
5
6
SELECT U.ID,
(SELECT ',' + C.ColumnGroupBy
FROM Table AS C
WHERE C.ID = U.ID
FOR XML PATH('')) AS TEMP
FROM TABLE_U U

加上過濾Distinct 和移除多餘 ,

1
2
3
4
5
6
SELECT DISTINCT U.ID,
STUFF((SELECT ',' + C.ColumnGroupBy
FROM Table AS C
WHERE C.ID = U.ID
FOR XML PATH('')) AS TEMP
FROM TABLE_U U,1,1,'')

參考連結

補充:
STUFF 用法:
STUFF(原字串, 起始位置, 移除長度, 替換字串)