Home > Database > Mysql Tutorial > How to Concatenate Text from Multiple Rows into a Single String in SQL Server?

How to Concatenate Text from Multiple Rows into a Single String in SQL Server?

Mary-Kate Olsen
Release: 2025-01-25 18:12:09
Original
452 people have browsed it

How to Concatenate Text from Multiple Rows into a Single String in SQL Server?

SQL Server merge multiple lines of text into a single line string

In various database scenarios, you may need to combine string values ​​from multiple rows into a single, coherent string. This is especially useful when you need to combine information from different data points into a comprehensive summary or display.

Problem Statement

Consider a table called "Names" that contains the following three rows:

  • Peter
  • Paul
  • Mary

Challenge

The goal is to convert these individual lines into a single comma-separated string: "Peter, Paul, Mary".

Solution

In SQL Server 2017 and Azure SQL Database, you can use the STRING_AGG() function to accomplish this task. The syntax of STRING_AGG() is as follows:

<code class="language-sql">STRING_AGG(<expression> [ , delimiter ] [ ORDER BY <expression> [ ASC | DESC ] ])</code>
Copy after login

For our scenario, the expression will be the name column and the delimiter will be a comma. The ORDER BY clause ensures that names appear in a specific order (that is, alphabetical order).

SQL Query

<code class="language-sql">SELECT STRING_AGG(Name, ', ') AS ConcatenatedNames
FROM Names
ORDER BY Name;</code>
Copy after login

Output

<code>ConcatenatedNames
---------------------
Peter, Paul, Mary</code>
Copy after login

Alternative solutions for earlier SQL Server versions

If you are using an earlier version of SQL Server, such as SQL Server 2005, you can use the following method:

<code class="language-sql">SELECT
    (
        SELECT StudentName + ',' AS [text()]
        FROM dbo.Students
        WHERE SubjectID = Main.SubjectID
        ORDER BY StudentID
        FOR XML PATH('')
    ).value('text()[1]', 'nvarchar(max)') AS Students
FROM
    (
        SELECT DISTINCT SubjectID
        FROM dbo.Students
    ) AS Main;</code>
Copy after login

The above is the detailed content of How to Concatenate Text from Multiple Rows into a Single String 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