SQL Server 函数实现字符串分割功能

字符串切分功能在许多语言中都有现成的函数可以调用
现在用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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值