拆分数据库字段中字符串,以表的形式返回

本文介绍了一个 SQL 函数 [dbo].[RecurrentSplit] 的实现细节,该函数用于将一个字符串按指定的分隔符进行分割,并返回分割后的结果。此函数支持自定义是否保留分隔符及分隔符的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
Create FUNCTION [dbo].[RecurrentSplit]
(
@nvStr nvarchar(2000)  --需要分割字符串
,@vSeparte varchar(50)  --分割字符串
,@iIsHaveSeparte int   --是否显示字符串
,@iIsBefore int    --是否是后面的分割符(分割字符分割的顺序)
)
RETURNS @Split table 
(
IndexNo 
int default(0)   --流水号
,SplitName nvarchar(1000)  --分割后字符串
)
AS
BEGIN
 
if(charindex(@vSeparte,@nvStr)<=0--处理在整个字符串里都没有要分割,也就是字符串本身
 begin
  
insert into @Split(SplitName) values(@nvStr)
  
return
 
end
 
declare @iSeparteLen int
 ,
@iEndHave int --最后几个字符串是否是分割字符
 ,@iStartHave int --前面几个字符串是否是分割字符
 select @iSeparteLen=len(@vSeparte)
 ,
@iStartHave=0
 ,
@iEndHave=0
 ,
@iIsHaveSeparte=case when @iIsHaveSeparte is null --默认值
  then 0 
  
else @iIsHaveSeparte 
  
end
 ,
@iIsBefore=case when @iIsBefore is null --默认值
  then 0 
  
else @iIsBefore 
  
end
 
if(@iIsBefore=1--只有在处理前面字符串分割时才用
 begin
  
if(left(@nvStr,@iSeparteLen)<>@vSeparte)--处理前面几个分割字符一定是分割字符,不是就加
  begin
   
select @nvStr=@vSeparte+@nvStr
   ,
@iStartHave=1
  
end
 
end
 
if(right(@nvStr,@iSeparteLen)<>@vSeparte)--处理最后几个分割字符一定是分割字符,不是就加
 begin
  
select @nvStr=@nvStr+@vSeparte
  ,
@iEndHave=1
 
end--分号一定不能少,因为用了with,是用公用表达式,在其前面一定要加;
 
 
with CharCET(CharStr,StrLen,IndexNo)
 
as
 (
  
select substring(@nvStr,0
  ,
case when @iIsBefore=0 then charindex(@vSeparte,@nvStr)+@iSeparteLen
  
else charindex(@vSeparte,@nvStr,charindex(@vSeparte,@nvStr)+@iSeparteLenend
  ) CharStr
  ,
case when @iIsBefore=0 then charindex(@vSeparte,@nvStr
  
else charindex(@vSeparte,@nvStr,charindex(@vSeparte,@nvStr)+@iSeparteLenend StrLen
  ,
0 IndexNo  --第一次初始化
  union all
  
select substring(@nvStr
  ,
case when @iIsBefore=0 then StrLen+@iSeparteLen 
  
else StrLen end
  ,
charindex(@vSeparte,@nvStr,StrLen+@iSeparteLen)-StrLen) CharStr 
  ,
charindex(@vSeparte,@nvStr,StrLen+@iSeparteLen) StrLen
  ,IndexNo
+1 IndexNo --进行递归分割字符串
  from CharCET
  
where StrLen<len(@nvStr)-@iSeparteLen --处理递归结束语句,也就是不要让其生成无限弟归下去
 )
 
insert into @Split(IndexNo,SplitName)
 
select IndexNo,case when @iIsHaveSeparte=0 
  
then replace(CharStr,@vSeparte,''
  
else CharStr 
  
end CharStr
 
from CharCET 
 
if(@iIsHaveSeparte=1--是否显示分割字符串
 begin
  
update @Split --处理前面的分割字符串
  set SplitName=case when @iStartHave=1 
   
then replace(SplitName,@vSeparte,''
   
else SplitName 
   
end
  
where IndexNo = 0

  
update @Split --处理后面的分割字符串
  set SplitName=case when @iEndHave=1 
   
then replace(SplitName,@vSeparte,''
   
else SplitName 
   
end
  
where IndexNo = (select Max(IndexNo) from @Split)
 
end
 
RETURN 
END
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值