字符串切分功能在许多语言中都有现成的函数可以调用
现在用T-SQL的表值函数实现一下:
CREATE function split
(
@strList varchar(500),
@deli char(1)
)
returns @result table( obj varchar(500))
as
begin
declare @tmp table(idx int,chr char(1),obj varchar(500))
insert into @tmp(chr)
select substring(@strList,i,1) from nums
where i <= len(@strList)
declare @idx int, @obj varchar(500)
set @idx = 1
set @obj =''
update @tmp set
@idx=idx= case chr when @deli then @idx+1 else @idx end,
@obj=obj= case chr when @deli then '' else @obj+chr end
insert into @result(obj) select max(obj) from @tmp group by idx
return
end
在这个实现中使用了一个整数表 nums。sql server中没有这个表,需要自已动手创建。
其内容如下:
该表只有一个字段 ,字段名 i , 这一列存放整数值。
通过这个表,可以将一个字符串分解成单个字符组成的数据行
select substring(@strList,i,1) from nums
where i <= len(@strList)
将分解出来的单个字符存放表变量中:
insert into @tmp(chr)
select substring(@strList,i,1) from nums
where i <= len(@strList)
接下来使用了一个小技巧,update 配合 临时变量,case表达式 查找 分隔符
update @tmp set
@idx=idx= case chr when @deli then @idx+1 else @idx end,
@obj=obj= case chr when @deli then '' else @obj+chr end
最后通过分组查询,找出每一组中最长的哪一行,就是被分隔符分隔的部分
select max(obj) from @tmp group by idx