Home > Database > Mysql Tutorial > How to Concatenate Rows with a Comma Delimiter in SQL Server?

How to Concatenate Rows with a Comma Delimiter in SQL Server?

Mary-Kate Olsen
Release: 2025-01-16 23:32:10
Original
564 people have browsed it

How to Concatenate Rows with a Comma Delimiter in SQL Server?

Join rows using comma delimiter in SQL Server

This article explains how to merge multiple rows of data into a comma-separated string in SQL Server. In MS SQL Server, this can be effectively achieved by using a combination of STUFF and FOR XML functions.

Here is a sample table (@T):

<code class="language-sql">DECLARE @T AS TABLE
(
    Name varchar(10)
)

INSERT INTO @T VALUES
('John'),
('Vicky'),
('Sham'),
('Anjli'),
('Manish')</code>
Copy after login

To concatenate the names into a comma-separated string, execute the following query:

<code class="language-sql">SELECT STUFF((
    SELECT ',' + Name
    FROM @T
    FOR XML PATH('')
), 1, 1, '') As [output];</code>
Copy after login

This query utilizes FOR XML to generate an XML hierarchy of names, and then utilizes the STUFF function to construct the final string. The output will be:

<code>output
John,Vicky,Sham,Anjli,Manish</code>
Copy after login

This method effectively concatenates multiple rows of data into a single string, making it ideal for tasks such as generating comma-separated lists or exporting data in a specific format.

The above is the detailed content of How to Concatenate Rows with a Comma Delimiter in SQL Server?. 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