This approach is slightly better as it just sorts id, notid,name
;WITH cte AS
(
SELECT DISTINCT id
FROM
)
SELECT id, STUFF((SELECT ', ' + CAST(t2.name AS NVARCHAR(MAX))
FROM
FOR XML PATH('')),1,1,'') name
FROM cte t1
If you have a table containing only individual fields id, you probably would be better off using this.
The approach that you use, only works properly if the data is guaranteed not to contain any characters, such as <, >,&
source
share