SQL Server aggregates strings

Source: Internet
Author: User
Keyword: sqlserver2012, FORXMLPATH, connection string you may have encountered the need to aggregate strings in your work, for example: the actual table data is as follows: Name Development Department Zhang San Development Department Li Si Finance Department Wang 2 Finance Department MA sub Operation Department Lu manjia and then through aggregation, the expected result is development of name

Keyword: sqlserver 2012, for xml path, connection string you may have encountered the need to aggregate strings in your work, FOR example: the actual table data is as follows: depart name Development Department Zhang San Development Department Li Si Finance Department Wang 2 Finance Department MA sub Operation Department Lu manjia and then through aggregation, the expected result is depart name development.

Keywords: sqlserver 2012, for xml path, connection string

You may have encountered the need to aggregate strings at work, for example:

The actual table data is as follows:

Depart Name
Development Department Zhang San
Development Department Li Si
Finance Department Wang 'er
Finance Department Ma Zi
Operation Department Lu renjia

Then, through aggregation, the expected results

Depart Name
Development Department Zhang San, Li Si
Finance Department Wang 'er, Ma Zi
Operation Department Lu renjia

In fact, there are three ways to achieve this.

1. Use a custom function)

2. Use cursor)

3. Use the for xml path Function

This article mainly introduces the third type, Because theoretically the complexity and overhead of the Code are relatively small.

The Code is as follows:

select depart, [name]=stuff((select','+[name]from tb t where id = tb.depart for xml path('')) , 1 , 1 , '') from tb groupby depart

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.