SQL Server merges multiple rows of data into one line: using the self-connect, for XML PATH ("), stuff, or replace function

Source: Internet
Author: User
Tags first string

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.