How to concatenate text from multiple rows into a single text string in SQL Server
Richard C.
—Imagine you have a table in MS SQL Server with a column containing many strings in multiple rows. How do you display them concatenated in one line?
Assume you have a table called Person
with a Name
column like the following:
CREATE TABLE Person ( Id INT PRIMARY KEY, Name VARCHAR(255) ); INSERT INTO Person(Id, Name) VALUES (1, 'Amir'), (2, 'Sofia'), (3, 'Aya'), (4, 'Mateo'), (5, 'Leila'), (6, 'Yara'), (7, 'Ndidi'), (8, 'Santiago');
If you want to display all the names in one string and you are using SQL Server after 2017, you can use the STRING_AGG
function to concatenate multiple rows:
SELECT STRING_AGG(Name, ', ') AS Names FROM Person; -- Names -- Amir, Sofia, Aya, Mateo, Leila, Yara, Ndidi, Santiago
If you are using an earlier version of SQL Server you can use XML:
SELECT Name + ', ' AS 'data()' FROM Person FOR XML PATH(''); -- XML_F52E2B61-18A1-11d1-B105-00805F49916B -- Amir, Sofia, Aya, Mateo, Leila, Yara, Ndidi, Santiago
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].
If you are a California resident, see our Supplemental notice.