string_agg for sql server pre 2017

我只是一个虾纸丫 提交于 2019-11-26 23:28:09

问题


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 Tabel t

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


回答1:


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.



来源:https://stackoverflow.com/questions/49361088/string-agg-for-sql-server-pre-2017

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!