Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String_agg for SQL Server before 2017

Can anyone help me make this query work for SQL Server 2014?

This is working on Postgresql and probably on SQL Server 2017. On Oracle it is listagg instead of string_agg.

Here is the SQL:

select 
    string_agg(t.id,',') AS id
from 
    Table t

I checked on the site some xml option should be used but I could not understand it.

like image 930
Master Yi Avatar asked Mar 19 '18 10:03

Master Yi


People also ask

How aggregate function works in SQL?

An aggregate function performs a calculation on a set of values, and returns a single value. Except for COUNT(*) , aggregate functions ignore null values. Aggregate functions are often used with the GROUP BY clause of the SELECT statement. All aggregate functions are deterministic.

What is STRING_AGG in SQL Server?

STRING_AGG is an aggregate function that takes all expressions from rows and concatenates them into a single string. Expression values are implicitly converted to string types and then concatenated. The implicit conversion to strings follows the existing rules for data type conversions.

How do I split a string in SQL?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument. FROM STRING_SPLIT( 'An example sentence.

When was STRING_AGG added?

The STRING_AGG function concatenates strings separated by a specified separator. This was introduced with SQL Server 2017.


1 Answers

In SQL Server pre-2017, you can do:

select stuff( (select ',' + cast(t.id as varchar(max))
               from tabel t
               for xml path ('')
              ), 1, 1, ''
            );

The only purpose of stuff() is to remove the initial comma. The work is being done by for xml path.

like image 152
Gordon Linoff Avatar answered Oct 14 '22 13:10

Gordon Linoff