Home >Database >Mysql Tutorial >How to Efficiently Concatenate SQL Query Results into a Single String?

How to Efficiently Concatenate SQL Query Results into a Single String?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-03 09:42:43210browse

How to Efficiently Concatenate SQL Query Results into a Single String?

Accumulating SQL Query Results into a Single String

Concatenating query results into a single string is a common task in database programming. In SQL Server, there are two approaches to achieve this: using the FOR XML PATH & STUFF technique or leveraging the STRING_AGG function.

FOR XML PATH & STUFF

For SQL Server versions 2005 and above, the FOR XML PATH & STUFF combination is an effective approach:

DECLARE @CodeNameString varchar(100)

SELECT 
   @CodeNameString = STUFF( (SELECT ',' + CodeName 
                             FROM dbo.AccountCodes 
                             ORDER BY Sort
                             FOR XML PATH('')), 
                            1, 1, '')

This solution concatenates the results using FOR XML PATH('') into an XML string, then uses STUFF to remove the initial comma inherited from the XML concatenation.

STRING_AGG Function

In SQL Server 2017 and later, the STRING_AGG function provides a dedicated solution for this task:

DECLARE @CodeNameString varchar(100)

SELECT 
   @CodeNameString = STRING_AGG(CodeName, ',')
FROM 
   dbo.AccountCodes
ORDER BY 
   Sort

The STRING_AGG function concatenates the results directly into a single string, separated by the specified delimiter (in this case, ',').

Handling Special Characters

It's important to note that the FOR XML PATH & STUFF approach may encode certain special characters, such as '<', '>', and '&', into XML entities (<, >, and &). For situations where these characters are problematic, the STRING_AGG function with the USING XMLTYPE clause can be used:

DECLARE @CodeNameString varchar(100)

SELECT 
   @CodeNameString = STRING_AGG(CodeName, ',') USING XMLTYPE
FROM 
   dbo.AccountCodes
ORDER BY 
   Sort

The above is the detailed content of How to Efficiently Concatenate SQL Query Results into a Single String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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