How to concatenate text from multiple rows into a single text string in the SQL Server 2017 and later?
By using STRING_AGG
function, we can concatenate text from multiple rows into a single text string without writing any custom SQL queries. The separator will not add at the end of the string.
This function introduced in SQL Server 2017.
Syntax:
STRING_AGG(expression, separator) Returns nvarchar(max);
Consider a database table dbo.Students
holding student names, with four rows:
StudentName |
---|
Peter |
NULL |
Paul |
Mary |
Example 1:
SELECT STRING_AGG(S.StudentName, ',') AS [Student Names]
FROM @Students S
Output:
Peter,Paul,Mary
Example 2: With Sorted list
SELECT STRING_AGG(S.StudentName, ',') WITHIN GROUP (ORDER BY S.StudentName) AS [Student Names]
FROM @Students S
Output:
Mary,Paul,Peter
Full Query:
DECLARE @Students TABLE(StudentName VARCHAR(100))
INSERT INTO @Students(StudentName)
VALUES ('Peter'),
(NULL),
('Paul'),
('Mary')
SELECT STRING_AGG(S.StudentName, ',') AS [Student Names]
FROM @Students S
-- With Sorted list
SELECT STRING_AGG(S.StudentName, ',') WITHIN GROUP (ORDER BY S.StudentName) AS [Student Names]
FROM @Students S
Note: The
GROUP BY
clause is required if theSTRING_AGG
function isn't the only item in theSELECT
list.
Generate list of emails per towns
The following query finds the email addresses of employees and groups them by towns:
SELECT town, STRING_AGG (email, ';') AS emails
FROM dbo.Employee
GROUP BY town;
Output:
town | emails |
---|---|
Seattle | test-user1@adventure-works.com;test-user2@adventure-works.com;test-user3@adventure-works.com |
LA | test-user4@adventure-works.com;test-user5@adventure-works.com |
-
CreatedJan 18, 2020
-
UpdatedNov 03, 2020
-
Views1,671
Related Articles
Different types of variables in SQL Server
What is Cross Join in SQL Server
How delete record from parent table when there is Foreign Key relation in SQL Server
What is the differences between CHAR, NCHAR, VARCHAR and NVARCHAR in SQL Server?
How to add or remove a column from a table in SQL Server?
How to insert values into Identity Column in SQL Server?
How to get a fixed-length value in SQL Server?
What is Left Join (or) Left Outer Join in SQL Server?
How to get current week dates in SQL Server?
What are the different types of Date formats in SQL Server?