Comprehensive Methods for Converting Multiple Rows to Comma-Separated Values in SQL Server

Nov 18, 2025 · Programming · 11 views · 7.8

Keywords: SQL Server | Comma-Separated Values | FOR XML PATH | STRING_AGG | Data Aggregation

Abstract: This article provides an in-depth exploration of various techniques for aggregating multiple rows into comma-separated values in SQL Server. It thoroughly analyzes the FOR XML PATH method and the STRING_AGG function introduced in SQL Server 2017, offering complete code examples and performance comparisons. The article also covers practical application scenarios, performance optimization suggestions, and best practices to help developers efficiently handle data aggregation requirements.

Introduction

In database development, there is often a need to aggregate multiple rows of data into a single comma-separated string. This requirement is particularly common in scenarios such as report generation, data export, and front-end display. SQL Server provides multiple implementation methods, which this article will systematically introduce.

FOR XML PATH Method

In versions prior to SQL Server 2017, FOR XML PATH was the standard method for handling the conversion of multiple rows to comma-separated values. This method utilizes XML functionality to achieve string concatenation.

The basic syntax structure is as follows:

SELECT STUFF((SELECT ', ' + CAST(column_name AS VARCHAR(length)) FROM table_name WHERE conditions FOR XML PATH('')), 1, 2, '')

Let's understand the implementation details of this method through a specific example:

DECLARE @SampleTable TABLE(ID INT, Value INT);INSERT INTO @SampleTable VALUES (1,100),(1,200),(1,300),(1,400);SELECT ID, STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) FROM @SampleTable WHERE ID = outer_table.ID FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'), 1, 2, '') AS List_OutputFROM @SampleTable outer_tableGROUP BY ID;

In this implementation, FOR XML PATH('') converts the query results to XML format, and the STUFF function is used to remove the extra delimiter at the beginning. The TYPE directive ensures proper handling of special characters, avoiding XML escape issues.

STRING_AGG Function

SQL Server 2017 introduced the STRING_AGG function, which greatly simplifies string aggregation operations. This built-in function is specifically designed to handle comma-separated value generation requirements.

Basic syntax:

SELECT STRING_AGG(column_name, separator) FROM table_name GROUP BY group_column

Usage example:

DECLARE @SampleTable TABLE(ID INT, Value INT);INSERT INTO @SampleTable VALUES (1,100),(1,200),(1,300),(1,400);SELECT ID, STRING_AGG(Value, ', ') AS List_OutputFROM @SampleTableGROUP BY ID;

The STRING_AGG function automatically handles NULL values, ignoring them by default, but sorting can be controlled via the WITHIN GROUP clause. Compared to the FOR XML PATH method, STRING_AGG offers better readability and performance.

Performance Comparison Analysis

In practical applications, there are significant performance differences between the two methods. STRING_AGG, as a native aggregate function, outperforms the FOR XML PATH method in execution efficiency, especially when processing large amounts of data.

Performance tests show that STRING_AGG typically reduces query execution time by 30%-50% compared to FOR XML PATH, while also consuming less memory resources. This is mainly due to STRING_AGG's underlying optimizations and direct string processing mechanism.

Practical Application Scenarios

Consider a product management system that needs to aggregate multiple items related to a product into a comma-separated string:

CREATE TABLE #Products (ProductID INT, ProductKey INT);INSERT INTO #Products VALUES (123456, 12), (213432, 23), (213342, 25);CREATE TABLE #Items (ProductKey INT, ItemName VARCHAR(50));INSERT INTO #Items VALUES (12, 'Printer'), (23, 'Stapler'), (23, 'Printer'), (25, 'Remote'), (25, 'Laptop');SELECT ProductID, STUFF((SELECT ',' + ItemName FROM #Items inner_table WHERE inner_table.ProductKey = outer_table.ProductKey FOR XML PATH('')), 1, 1, '') AS ItemListFROM #Products outer_table;

This query will return: 123456-Printer, 213432-Stapler,Printer, 213342-Remote,Laptop.

Best Practices Recommendations

When choosing an implementation method, consider the following factors: SQL Server version compatibility, data volume, performance requirements, and code maintainability. For new projects, it is recommended to prioritize the use of the STRING_AGG function. For situations requiring backward compatibility, FOR XML PATH remains a reliable choice.

When handling large amounts of data, it is advisable to establish appropriate indexes on relevant columns to optimize query performance. Additionally, be mindful of the performance overhead that may arise from data type conversions and try to use appropriate data type lengths.

Conclusion

SQL Server provides powerful tools to handle the conversion of multiple rows to comma-separated values. The FOR XML PATH method performs stably in older versions, while the STRING_AGG function offers a more elegant solution in newer versions. Developers should choose the appropriate method based on specific requirements and environment to ensure code efficiency and maintainability.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.