I have the following code which will create a comma delimited list for my results:
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+', ' ,'') + INSTITUTIONNAME
FROM EDUCATION
WHERE STUDENTNUMBER= '111'
SELECT @listStr
The problem is its creating one massive comma delimited line. I need it to return a comma separated list per row.
So if Simon
has been part of 2 institutions, then i expect:
"INSTITUTION1, INSTITUTION2"
As i didnt supply a where clause i expect my results to show up like this for each row in the database.
I just saw another question very similar to this!
Here is the canonical NORTHWIND (spelled just slightly different for some reason) database example.
Use
FOR XML PATH('')
and STUFF() as follows Which gives you the same comma seperated resultHere is the FIDDLE
For Sql Server 2017 and later you can use the new
STRING_AGG
functionhttps://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql
Perhaps a more common use case is to group together and then aggregate, just like you would with
SUM
,COUNT
orAVG
.