Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of String.Join on TSQL? [duplicate]

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'
like image 783
Gil Avatar asked May 29 '11 21:05

Gil


People also ask

What is the replacement of join in SQL?

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.

Can a LEFT join create duplicates?

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).

How do I concatenate multiple rows in a single string in SQL?

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.


2 Answers

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
like image 127
domager Avatar answered Oct 18 '22 11:10

domager


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()

like image 27
Hogan Avatar answered Oct 18 '22 11:10

Hogan