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