0

I want to create a view where an entry in my view is a concatenated string. In this case, it is ParticipantNames.

I have two tables. A Trips table and a Participants table. One trip can have one to many participants. So in my Participant table I have multiple rows that are related to a single entry in the Trip table.

Is it possible to create a string that concatenates the names from all the participants and insert that into the ParticipantNames column? e.g "Hans, Ben, Ali"

CREATE OR ALTER VIEW TripView 
AS
    SELECT
        Id  = Trip .Id,
        ParticipantNames = ???
    FROM    
        [dbo].Trip Trip 
    LEFT JOIN 
        [dbo].[Participants] Participants ON Participants.TripId = Trip.Id

2 Answers 2

3

You can use string_agg() in the more recent versions of SQL Server:

 SELECT t.Id, string_agg(p.name, ', ') as ParticipantNames
 FROM  [dbo].Trip t LEFT JOIN 
       [dbo].[Participants] p
       ON p.TripId = t.Id
 GROUP BY t.Id;
Sign up to request clarification or add additional context in comments.

6 Comments

Where should i write this? If i write it above where i am creating my view it says "CREATE VIEW MUST BE THE ONLY STATEMENT IN THIS BATCH"
You need a GO before the CREATE VIEW.
Okay..and the thing you wrote where should i place it? It says: A fatal scripting error occurred. Incorrect syntax was encountered while parsing GO.
@Xraycat922 . .. This query seems syntactically correct.
To answer my own question - yes you can.
|
3

For versions earlier than SQL Server 2017, you can use FOR XML PATH, for string concatenation

SELECT 
    T.Id, 
    STUFF((SELECT ','+p.name
           FROM dbo.participants p
           WHERE p.TripId = T.Id
           FOR XML PATH('')), 1, 1, '') AS ParticipantNames
FROM [dbo].Trip T
GROUP BY T.Id;

From SQL Server 2017 onwards, you can go ahead with Gordon Linoff solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.