SQL中字符串拆分成獨立的多個字符串

8 篇文章 0 订阅

create table #ie_Department_Manager(Empl_Index nvarchar(10),Dep_Code nvarchar(200))
insert into #ie_Department_Manager values('656','AS011')
insert into #ie_Department_Manager values('657','AS011/AS012/AS013/AS021/AS022/AS023')
insert into #ie_Department_Manager values('658','AS011/AS012/AS013/AS021/AS022/AS023/AC011/AC012/AC013/AC021/AC022/AC023')
create table #tmpPersonForDep(Empl_Index nvarchar(10),Dep_Code nvarchar(20))
create table #tmpPersonForDep2(Empl_Index nvarchar(10),Dep_Code nvarchar(20))

declare tmpManager cursor for
select empl_index,Dep_Code from #ie_Department_Manager
order by Dep_Code

declare @Empl_Index nvarchar(10),@Dep_Code nvarchar(200),@position int,@index int

open tmpManager
fetch next from tmpManager
into @Empl_Index,@Dep_Code

while @@FETCH_STATUS = 0
begin
 --法一:Replace命令
 declare @comm nvarchar(4000)
 set @comm='insert   into  #tmpPersonForDep  values   ('+@Empl_Index+',''')+''')'  
 --print @Empl_Index+'~'+@Dep_Code
 --print @comm
 execute (@comm)
 
 --法二:CharIndex命令
 set @position=charindex('/',@Dep_Code)
 if right(@Dep_Code,1)<>'/'
 begin
  set @Dep_Code=@Dep_Code+'/'
  set @position=charindex('/',@Dep_Code)
 end
 set @index=1
 while @position>0
 begin
--  select @empl_index,@dep_code,substring(@Dep_Code,@Index,@position-@Index)
  insert   into  #tmpPersonForDep2  values(@empl_Index,substring(@Dep_Code,@Index,@position-@Index))
  set @Index=@position+1
  set @position=charindex('/',@Dep_Code,@Index)
 end

 fetch next from tmpManager
 into @Empl_Index,@Dep_Code
end
select * from #tmpPersonForDep
select * from #tmpPersonForDep2
close tmpManager
deallocate tmpManager
drop table #tmpPersonForDep
drop table #tmpPersonForDep2
DROP TABLE #ie_Department_Manager

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值