SQL Server 2016中的String_agg

sha*_*ane 6 sql sql-server string-aggregation sql-server-2016

这是我在SQL Server 2016中的代码

insert into @entdef_queries(entitydefid,squery)
            select A.entitydefid
                ,
                (
                    select String_agg(cols,ioperator)
                    from
                    (
                        Select case when lower(b.metricdatatype) like 'string%' or lower(b.metricdatatype) like '%char%' or lower(b.metricdatatype) ='bit' or lower(b.metricdatatype) like 'date%' then
                                ' lower("'+ b.metricname +'") ' + b.metriccondition +' '''+ b.value1 +''' ' 
                            when lower(b.metricdatatype) not like 'string%' and lower(b.metricdatatype) like '%char%' and lower(b.metricdatatype) !='bit' and lower(b.metricdatatype) not like 'date%' then 
                                case when lower(b.metriccondition)='between' then  ' "'+ b.metricname +'"' + b.metriccondition +' '+ b.value1 +' and ' + b.value2 + ' '
                                    else ' "'+ b.metricname +'"' + b.metriccondition +'  '+ b.value1 + ' ' end  
                            end cols
                        , ( select distinct operators from @entdef_data C where A.entitydefid=C.entitydefid) ioperator
                        from 
                        @entdef_data B
                        where A.entitydefid=b.entitydefid
                    )inp
                )
            from
            @entdef_data A
            group by A.entitydefid;   
Run Code Online (Sandbox Code Playgroud)

当我尝试执行以下代码时,它引发错误String_agg不是内置函数。

Ale*_*lok 5

正如 Gordon Linoff 提到的,此功能在 SQL Server 2016 中不可用。

for xml方法是要使用的。


从 SQL Server 2005 开始,可以使用一个稍 快的SQLCLR GROUP_CONCAT替代方案: 。其用法与本机 STRING_AGG 非常相似。但因为它是自定义的 CLR 聚合,所以它引入了自身的风险:启用 CLR、可能的内存泄漏等。

文档: https: //orlando-colamatteo.github.io/ms-sql-server-group-concat-sqlclr/