將包含分號的欄位值拆分成多條記錄
將包含分號的欄位值拆分成多條記錄
xx,yy,zz三個欄位中的內容如果分號分隔的個數相同(以xx欄位為基準),則按先後順序拆分記錄,如果分號分隔的個數與xx欄位不同的,則按xx欄位的分隔的個數拆分記錄,與其個數不等的原樣不變
drop table #aa
go
create table #aa(xx varchar(200),yy varchar(200),zz varchar(200))
insert #aa
select '1;2;3','好;中;差','山東;北京;上海'
union all
select '4;5','好;中','廣東;河南;安徽'
union all
select
union all
select '9','差','湖北'
union all
select '10;11','好;差','福建;青海'
go
--> 顯示原資料
select * from #aa
/*原資料
xx yy zz
-------------------------------------------
1;2;3 好;中;差 山東;北京;上海
4;5 好;中 廣東;河南;安徽
6;7;8 中;差 江西;河北;湖南
9 差 湖北
10;11 好;差 福建;青海
(5 行受影響)
--> 程式碼實現
declare @temp table(xx int,yy varchar(20),zz varchar(20)) --> 建立臨時表來儲存結果
declare @xx varchar(20),@yy varchar(20),@zz varchar(20),@x varchar(20),@y varchar(20),@z varchar(20)
declare my_cursor cursor for select * from #aa --> 宣告遊標
open my_cursor
fetch next from my_cursor
while @@fetch_status=0
begin
declare @a varchar(20),@b varchar(20),@c varchar(20)
select @a=@xx,@b=@yy,@c=@zz
while(len(@xx)>0)
begin
if charindex(';',@xx)>0
begin
if len(@a)-len(replace(@a,';',''))<>len(@b)-len(replace(@b,';',''))
select @x=left(@xx,(charindex(';',@xx)-1)),@y=@yy
else
select @x=left(@xx,charindex(';',@xx)-1),@y=left(@yy,charindex(';',@yy)-1),@yy=stuff(@yy,1,charindex(';',@yy),'')
if len(@a)-len(replace(@a,';',''))<>len(@c)-len(replace(@c,';',''))
select @x=left(@xx,charindex(';',@xx)-1),@z=@zz
else
select @x=left(@xx,charindex(';',@xx)-1),@z=left(@zz,charindex(';',@zz)-1),@zz=stuff(@zz,1,charindex(';',@zz),'')
insert into @temp select @x,@y,@z
set @xx=stuff(@xx,1,charindex(';',@xx),'')
end
else
begin
insert into @temp select @xx,@yy,@zz
set @xx=''
end
end
fetch next from my_cursor into @xx,@yy,@zz
end
deallocate my_cursor
--> 顯示結果資料
select * from @temp
/*結果資料
xx yy zz
-------------------------------
1 好 山東
2 中 北京
3 差 上海
4 好 廣東;河南;安徽
5 中 廣東;河南;安徽
6 中;差 江西
7 中;差 河北
8 中;差 湖南
9 差 湖北
10 好 福建
11 差 青海
(11 行受影響)
*/