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

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

Mary-Kate Olsen
Release: 2025-01-25 18:02:10
Original
914 people have browsed it

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

SQL Server Multiline Text Connection: XML PATH Method

The need to combine multiple lines of text data into a single string is common. For example, there is a table containing names:

<code>Peter
Paul
Mary</code>
Copy after login

The goal is to convert this into a unified string: "Peter, Paul, Mary".

For SQL Server 2017 or Azure users, consider the solution provided by Mathieu Renda. However, for earlier versions (such as SQL 2005), the XML PATH method provides an efficient method for this connection task.

The following is an example of a table called STUDENTS:

SubjectID StudentName
1 Mary
1 John
1 Sam
2 Alaina
2 Edward

Desired output is:

SubjectID StudentName
1 Mary, John, Sam
2 Alaina, Edward

To achieve this, use the following T-SQL code:

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

This query retrieves the SubjectID and concatenated StudentName values ​​and omits the trailing comma from the result string.

Alternatively, you can use a cleaner approach by concatenating the commas at the beginning and using STUFF to remove the first comma:

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

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