|
发表于 2020-1-15 20:00:01
|
显示全部楼层
--建立测试数据
create table test_1(id int, name char(10), class varchar(50))
go
insert test_1
select 12, 'a', '34||35||36' union all
select 13, 'b', '34||36' union all
select 14, 'c' , '33||34' union all
select 15, 'd', '34||35' union all
select 16, 'e', '34' union all
select 17, 'f', '34||37'
go
create table test_2(id int, name char(10), class varchar(50))
go
--执行更新并将结果循环插入临时表test_2
select 1
while @@rowcount > 0
--当执行begin...end语句块时,执行后影响的行数为0表示已将test_1表的class字段清空,循环完毕
begin
insert test_2
select id,name,class
from test_1
where charindex('|',class)=0 and class <>''
insert test_2
select id,name,left(class,charindex('|',class)-1) as class -- 取第一个class名称
from test_1
where charindex('|',class)>0
update test_1 set class = ''
where charindex('|',class)=0
update test_1 set
class = substring(class,charindex('|',class)+2,len(class)-charindex('|',class))-- 取除第一个class外的所有class
where charindex('|',class)>0
end
go
--查看临时表结果
select * from test_2
order by id,name,class
--删除测试环境
drop table test_1,test_2
--临时表结果
/*
id name class
12 a 34
12 a 35
12 a 36
13 b 34
13 b 36
14 c 33
14 c 34
15 d 34
15 d 35
16 e 34
17 f 34
17 f 37
*/ |
|