Example of merging a field value in SQL Server _mssql

Source: Internet
Author: User

The table is as follows:

How to get the following results:

Solution

Using XML transformations

The code is as follows:

Copy Code code as follows:

CREATE TABLE Body

(

ID int,

Body nvarchar (20)

)

Go

INSERT into the body VALUES (1, ' AAAA ')

INSERT into the body VALUES (2, ' bbbb ')

INSERT into the body VALUES (1, ' CCCCCC ')

INSERT into the body VALUES (3, ' ddddd ')

Go

SELECT * from body

SELECT DISTINCT A.id,stuff (SELECT, ' +body from the body WHERE id=a.id for XML Path ('), 1,1, ') asbody

From

Body A

--The concrete idea is this:

SELECT ', ' +body from the body WHERE id=a.id for XML Path (')

--The purpose of this statement is to look up all the records in the body table by the ID in a, and convert it into an XML (an article about converting a query set into XML, you can see) id=a.id

Stuff (SELECT ', ' +body from the body WHERE id=a.id for XML Path (')), 1, 1, ' "

The function of this statement is to remove and convert a comma in front of the generated XML into a scalar value

--end with a distinct to remove duplicate records

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.