Home > Database > Mysql Tutorial > How to Concatenate Rows with Commas in MSSQL Server?

How to Concatenate Rows with Commas in MSSQL Server?

Mary-Kate Olsen
Release: 2025-01-16 23:27:09
Original
782 people have browsed it

How to Concatenate Rows with Commas in MSSQL Server?

Use comma to join rows in MSSQL Server

Querying and merging multiple rows into a single comma separated string in MSSQL Server can be achieved using a combination of STUFF and FOR XML functions. The specific method is as follows:

Create a sample table and populate the values:

<code class="language-sql">DECLARE @T AS TABLE
(
   Name varchar(10)
)
INSERT INTO @T VALUES
('John'),
('Vicky'),
('Sham'),
('Anjli'),
('Manish')</code>
Copy after login

Construct queries using STUFF and FOR XML:

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

This query concatenates the Name column of all rows in table @T into a single string. It uses FOR XML to convert the table into an XML representation, and then uses STUFF to concatenate the XML nodes (Name elements, with " " as delimiter) into a single string. The result is similar to:

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

The above is the detailed content of How to Concatenate Rows with Commas in MSSQL 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