Sample table TB data is as follows
ID value
—————
1 AA
1 BB
2 AAA
2 BBB
2 CCC
SELECT ID,
[Val] = (
SELECT [value] + ', '
From TB as B
WHERE b.id = a.id for XML PATH (")
)
From TB as a
Show results
1 AA,BB,
1 AA,BB,
2 AAA,BBB,CCC,
2 AAA,BBB,CCC,
2 AAA,BBB,CCC,
SELECT ID,
[Val]= (SELECT [value] + ', '
From TB as B
WHERE b.id = a.id
For XML PATH (")")
From TB as a
GROUP by ID
Show results
1 AA,BB,
2 AAA,BBB,CCC,
SELECT ID,
[Val]=stuff (SELECT ', ' +[value ')
From TB as B
WHERE b.id = a.id
For XML PATH (")"), 1, 1, ")
From TB as a
GROUP by ID
Show results
1 AA,BB
2 AAA,BBB,CCC
The STUFF function inserts a string into another string. It removes the specified length of characters from the starting position in the first string, and then inserts the second string at the beginning of the first string.
STUFF (character_expression, start, length, Character_expression_insert)
SELECT ID,
[Val]= REPLACE ((SELECT [value] as [data ()]
From TB as B
WHERE b.id = a.id
For XML PATH ("))," ', ', ')
From TB as a
GROUP by ID
The result is the same as above.
parsing: [Data ()] here is said to play a similar array of functions, the specific use of the further check.
If the perimeter is not wrapped with the Replace function, the returned result is the AAA BBB CCC, with spaces between each item, so finally replace all spaces with a comma with the Replace function.
SQL Server merges multiple rows of data into one line: using the self-connect, for XML PATH ("), stuff, or replace function