在SQL Server 2016中的String_agg函数

12

这是我在 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;   
当我尝试执行以下代码时,它会抛出一个错误 String_agg 不是内置函数。

8
string_agg() 函数是从2017版本开始提供的,而不是2016版本。要么升级SQL Server,要么使用 for xml 方法。 - Gordon Linoff
1个回答

5
正如Gordon Linoff所提到的,这个功能在SQL Server 2016中是不可用的。 应该使用"for xml"方法。

在SQL Server 2005及以上版本中,有一个稍微更快的替代方法可用: SQLCLR GROUP_CONCAT。使用方式与本地的STRING_AGG非常相似。但由于它是自定义的CLR聚合,因此会引入自己的风险:需要启用CLR,可能会出现内存泄漏等问题。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接