Home > Database > Mysql Tutorial > How to Concatenate SQL Server Database Rows into a Single Comma-Separated String?

How to Concatenate SQL Server Database Rows into a Single Comma-Separated String?

Barbara Streisand
Release: 2025-01-16 23:41:14
Original
878 people have browsed it

How to Concatenate SQL Server Database Rows into a Single Comma-Separated String?

Combining SQL Server Rows into a Single Comma-Separated String

Microsoft SQL Server offers an efficient method to concatenate rows from a table into a single string separated by commas. This is achieved using a combination of the STUFF and FOR XML functions.

Example:

Let's create a sample table and populate it with data:

<code class="language-sql">DECLARE @MyTable TABLE (
    ItemName VARCHAR(20)
);

INSERT INTO @MyTable (ItemName) VALUES
('Apple'),
('Banana'),
('Orange'),
('Grape'),
('Mango');</code>
Copy after login

Now, execute the following query to concatenate the ItemName column values into a single comma-separated string:

<code class="language-sql">SELECT STUFF((
    SELECT ',' + ItemName
    FROM @MyTable
    FOR XML PATH('')
), 1, 1, '') AS ConcatenatedItems;</code>
Copy after login

Output:

The query will produce the following result:

<code>ConcatenatedItems
Apple,Banana,Orange,Grape,Mango</code>
Copy after login

The above is the detailed content of How to Concatenate SQL Server Database Rows into a Single Comma-Separated String?. 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