How Stuff and 'For Xml Path' work in Sql Server

后端 未结 9 1336
盖世英雄少女心
盖世英雄少女心 2020-11-21 13:49

Table is:

+----+------+
| Id | Name |
+----+------+    
| 1  | aaa  |
| 1  | bbb  |
| 1  | ccc  |
| 1  | ffffd  |
| 1  | eee  |
+----+------+

9条回答
  •  情深已故
    2020-11-21 14:14

    SELECT ID, 
        abc = STUFF(
                     (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
                   ) 
    FROM temp1 GROUP BY id
    

    Here in the above query STUFF function is used to just remove the first comma (,) from the generated xml string (,aaa,bbb,ccc,ffffd,eee) then it will become (aaa,bbb,ccc,ffffd,eee).

    And FOR XML PATH('') simply converts column data into (,aaa,bbb,ccc,ffffd,eee) string but in PATH we are passing '' so it will not create a XML tag.

    And at the end we have grouped records using ID column.

提交回复
热议问题