Possible Duplicate:
Is there a way to create a SQL Server function to “join” multiple rows from a subquery into a single delimited field?
Hi all!
I'm looking for an easy way to concatenate 'n' values. Something like:
SELECT MyConcat(',', T.TextColumn)
FROM SomeTable AS T
WHERE T.SomeOtherColumn = SomeCondition
So if I have a table like:
SomeTable:
Id | TextColumn | SomeOtherColumn
----+------------+----------------
1 | Qwerty | Y
2 | qwerty | N
3 | azerty | N
4 | Azerty | Y
It would result in something like:
SQL:
SELECT MyConcat(';', T.TextColumn)
FROM SomeTable AS T
WHERE T.SomeOtherColumn = 'Y'
RESULT:
'Qwerty;Azerty'
A join returns a result table constructed from data from multiple tables. You can also retrieve the same result table using a subquery. A subquery is simply a SELECT statement within another select statement.
Again, if we perform a left outer join where date = date, each row from Table 5 will join on to every matching row from Table 4. However, in this case, the join will result in 4 rows of duplicate dates in the joined DataSet (see Table 6).
You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.
This should do the trick:
DECLARE @Result VARCHAR(MAX);
SELECT
@Result = CASE
WHEN @Result IS NULL
THEN T.TextColumn
ELSE @Result + ';' + T.TextColumn
END
FROM
SomeTable AS T
WHERE
T.SomeOtherColumn = 'Y';
SELECT @Result
SELECT CAST(TextColumn + ';' AS VARCHAR(MAX))
FROM SomeTable
WHERE SomeOtherColumn = 'Y'
FOR XML PATH ('')
If you don't like the trailing ;
you can remove the character from the result.
EDIT IN 2017
Many platforms now support the windowing function LISTAGG()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With