An instance of SQL server that combines a field value

Source: Internet
Author: User

The table is as follows:

Obtain the following results:

Solution

Use xml Conversion

The Code is as follows:

Copy codeThe Code is as follows: create table body

(

ID int,

BODY nvarchar (20)

)

Go

Insert into body VALUES (1, 'aaa ')

Insert into body VALUES (2, 'bbbbbb ')

Insert into body VALUES (1, 'cccccccc ')

Insert into body VALUES (3, 'ddddd ')

Go

SELECT * FROM body

SELECT distinct a. ID, stuff (SELECT ',' + body from body where id = a. id for xml path (''), 1, 1,'') ASBODY

FROM

Body

-- The specific idea is as follows:

SELECT ',' + body from body where id = a. id for xml path ('')

-- This statement is used to search for ID = a in the body table according to the ID in. all records of the ID, and convert it into an xml (you can refer to the article about converting the query set to xml)

Stuff (SELECT ',' + body from body where id = a. id for xml path (''), 1, 1 ,'')

-- This statement removes a comma before the generated xml and converts it to a scalar value.

-- Remove duplicate records with a distinct

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.