Home > Database > Mysql Tutorial > How to Perform String Aggregation in SQL Server Before 2017?

How to Perform String Aggregation in SQL Server Before 2017?

Susan Sarandon
Release: 2025-01-20 19:45:18
Original
837 people have browsed it

SQL Server 字符串聚合 (2017 年之前)

String aggregation in versions prior to SQL Server 2017

In various scenarios, there is a need for string aggregation. Databases like Postgresql provide simple string_agg functions to meet this need. However, in SQL Server versions prior to 2017, this function is missing and users need to find an alternative.

One solution is to take advantage of the XML PATH option. The following query demonstrates how to apply this approach in SQL Server 2014:

<code class="language-sql">select stuff( (select ',' + cast(t.id as varchar(max))
               from tabel t
               for xml path ('')
              ), 1, 1, ''
            );</code>
Copy after login

In this query, the only purpose of the stuff() function is to remove the leading comma. The actual work of string aggregation is performed by the for xml path expression. The result is a comma-separated list of ids generated from table t.

This approach may not be as intuitive as using the string_agg function, but it provides a viable alternative for string aggregation in versions of SQL Server that do not have the built-in function.

The above is the detailed content of How to Perform String Aggregation in SQL Server Before 2017?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template