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'
Answer
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
No comments:
Post a Comment