MS SQL Server的STRING_SPLIT和STRING_AGG函数

时间:2019-05-25 23:41:00 来源:互联网 作者: 神秘的大神 字体:

在较新版本的SQL中,出现有2个函数,STRING_SPLIT和STRING_AGG,前者是把带有分隔的字符串转换为表,而后者却是把表某一表转换为以某种字符分隔的字符串。

如下面:

DECLARE @str NVARCHAR(MAX) = N'ADS,ADFD,AGF,SDFGSFD,DSFG,RET,TRY,T,ADF,GSF,UY,QWERQ'


把它转存为表:

<img src="https://img2018.cnblogs.com/blog/28036/201905/28036-20190525231536727-944056012.png" alt="" class="img-responsive">

 

DECLARE @dump_data AS TABLE([value] NVARCHAR(MAX))
INSERT INTO @dump_data ([value])  SELECT [value] FROM STRING_SPLIT(@str,',')

 

反转,需要把临时表这列[value] 转换为一个字符串:

<img src="https://img2018.cnblogs.com/blog/28036/201905/28036-20190525232239905-103959332.png" alt="" class="img-responsive">

 

SELECT STRING_AGG([value], ',') 
FROM @dump_data

 

其实STRING_AGG这函数,还可以对新串联的字符进行排序:

<img src="https://img2018.cnblogs.com/blog/28036/201905/28036-20190525232436116-459216552.png" alt="" class="img-responsive">

 

SELECT STRING_AGG([value], ',') WITHIN GROUP (ORDER BY [value]) 
FROM @dump_data

 

如果你不想创建临时表,把拆分的数据插入临时表,步骤繁复。可以使用派生表来进行:

<img src="https://img2018.cnblogs.com/blog/28036/201905/28036-20190525233445234-1287862223.png" alt="" class="img-responsive">

SELECT STRING_AGG([value], ',') WITHIN GROUP (ORDER BY [value]) 
FROM (SELECT [value] FROM STRING_SPLIT(@str,',')) source 

 

或者使用一般资料表运算式CTE (Common Table Expression)

<img src="https://img2018.cnblogs.com/blog/28036/201905/28036-20190525233812385-889425108.png" alt="" class="img-responsive">

;WITH dump_data AS
(
    SELECT [value] FROM STRING_SPLIT(@str,',')
)
SELECT STRING_AGG([value], ',') WITHIN GROUP (ORDER BY [value]) 
FROM dump_data;