


How Can I Combine Multiple Subquery Rows into a Single Delimited Field in SQL Server?
Jan 22, 2025 am 12:19 AMSQL Server: Combining Multiple Subquery Rows into a Single Delimited Field
This article explores several methods for concatenating rows from a subquery into a single delimited field within SQL Server. We'll examine techniques suitable for different SQL Server versions.
Method 1: FOR XML PATH (SQL Server 2005 and later)
This classic approach uses FOR XML PATH
to efficiently concatenate results:
SELECT [VehicleID], [Name], STUFF((SELECT ', ' + [City] FROM [Location] WHERE (VehicleID = Vehicle.VehicleID) FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS Locations FROM [Vehicle]
Method 2: STRING_AGG (SQL Server 2017 and later)
For newer SQL Server versions, STRING_AGG
provides a more readable and often faster solution:
SELECT [VehicleID], [Name], STRING_AGG([City], ', ') AS Locations FROM [Vehicle] V JOIN [Location] L ON V.VehicleID = L.VehicleID GROUP BY [VehicleID], [Name]
Note the use of a JOIN
here for improved performance compared to a subquery in this specific case.
Method 3: Custom Function (All SQL Server Versions)
For maximum reusability across different SQL Server versions and scenarios, a custom function offers flexibility:
CREATE FUNCTION dbo.JoinRows (@Subquery NVARCHAR(MAX), @Delimiter NVARCHAR(1)) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @Result NVARCHAR(MAX) = ''; DECLARE @Row NVARCHAR(MAX); DECLARE @NextRow CURSOR; SET @NextRow = CURSOR FOR SELECT [Value] FROM OPENROWSET('SQLNCLI', 'Server=(local);Trusted_Connection=yes;', @Subquery); OPEN @NextRow; FETCH NEXT FROM @NextRow INTO @Row; WHILE @@FETCH_STATUS = 0 BEGIN SET @Result += @Row + @Delimiter; FETCH NEXT FROM @NextRow INTO @Row; END; CLOSE @NextRow; DEALLOCATE @NextRow; RETURN STUFF(@Result, LEN(@Result), LEN(@Delimiter), ''); -- Remove trailing delimiter END; GO
This function uses OPENROWSET
to execute the dynamic subquery. This is safer than directly executing dynamic SQL. The function can then be used like this:
SELECT VehicleID, Name, dbo.JoinRows((SELECT City FROM Location WHERE VehicleID = Vehicle.VehicleID), ',') AS Locations FROM Vehicle;
Choose the method that best suits your SQL Server version and performance requirements. For SQL Server 2017 and later, STRING_AGG
is generally recommended for its simplicity and performance. For older versions, or for more complex scenarios, the custom function provides a robust and reusable solution.
The above is the detailed content of How Can I Combine Multiple Subquery Rows into a Single Delimited Field in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reduce the use of MySQL memory in Docker

How do you alter a table in MySQL using the ALTER TABLE statement?

How to solve the problem of mysql cannot open shared library

What is SQLite? Comprehensive overview

Run MySQl in Linux (with/without podman container with phpmyadmin)

Running multiple MySQL versions on MacOS: A step-by-step guide

How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)?

How do I configure SSL/TLS encryption for MySQL connections?
