SQLServer2008 关于while循环

有这样一个表tbl

id  code name

11   a      aa/bb/cc

22   b      ee/rr/tt

需要将name段根据‘/’拆分开来,变成新的数据行

即:

id  code  name

11   a       aa

11   a       bb

......以下省略.....

先给该表加上序号,存入临时表

select ROW_NUMBER()OVER(ORDER BY T.code desc) 序号,* into #temp from tbl

 

--创建一个带有固定列的临时表

create table #temp2
(
  ID int,
  code varchar(50),
  name varchar(50)

)

--使用while循环

declare @name varchar(200)
declare @count int
declare @i int
select @count=COUNT(*) from #temp
set @i=1
while(@i<
=@count)
begin
   --逐行判断
   select @name=t.Name from #temp t where t.序号
=@i
   while(CHARINDEX('/',@name,1)!=0)
   begin
     insert into #temp2 select t.id,t.code,SUBSTRING(@name,1,CHARINDEX('/',@name,1)-1) from #temp t where t.序号
=@i
    
     set @name3=SUBSTRING(@name,CHARINDEX('/',@name,1)+1,LEN(@name)-len(SUBSTRING(@name,1,CHARINDEX('/',@name,1)))) 
   end
  
   if(CHARINDEX('/',@name,1)=0)
   begin
     insert into #temp2 select t.id,t.code,@name from #temp t where t.序号=@i
   end
   set @i=@i+1
end

select * from #temp2 

 

注意:

insert into #temp from XX      只能往已经存在的表里插入值

select * into #temp   可以往未创建的表里添加值

 

原文地址:https://www.cnblogs.com/xcxcxcxc/p/5541171.html