当前位置: 移动技术网 > IT编程>数据库>MSSQL > MS SQL Server的STRING_SPLIT和STRING_AGG函数

MS SQL Server的STRING_SPLIT和STRING_AGG函数

2019年05月26日  | 移动技术网IT编程  | 我要评论

爱在日月潭片头曲,向井阳太,extjs视频教程

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

如下面:

declare @str nvarchar(max) = n'ads,adfd,agf,sdfgsfd,dsfg,ret,try,t,adf,gsf,uy,qwerq'


把它转存为表:

 

declare @dump_data as table([value] nvarchar(max))
insert into @dump_data ([value])  select [value] from string_split(@str,',')

 

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

 

select string_agg([value], ',') 
from @dump_data

 

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

 

select string_agg([value], ',') within group (order by [value]) 
from @dump_data

 

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

select string_agg([value], ',') within group (order by [value]) 
from (select [value] from string_split(@str,',')) source 

 

或者使用一般资料表运算式cte (common table expression)

;with dump_data as
(
    select [value] from string_split(@str,',')
)
select string_agg([value], ',') within group (order by [value]) 
from dump_data;

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网