表1 col
11*22*33
22*33*44
33*55
44
表2 col1 col2 col3
11 22 33
22 33 44
33 55 NULL
44 NULL NULL
就是要把表1转化成表2的形式,但是表1中的col ,例如11*22*33是我自己测试的,不确定有多少项组成。也可能出现 col4 col5 ...。
先谢谢各位大虾帮忙 !分不够在加!
create table 表1( col varchar(200))
insert 表1
select '11*22*33' union all select
'22*33*44' union all select
'33*55' union all select
'44'
declare @i int
declare @j int
select @i=max(len(col)-len(replace(col,'*','')))+1 from 表1
update 表1 set col=col+REPLICATE('*',@i-len(col)+len(replace(col,'*',''))-1)
declare @sql varchar(8000)
declare @sql1 varchar(8000)
set @sql='create table #t('
set @j=1
while @j<=@i
begin
set @sql=@sql+'col'+cast(@j as varchar)+' varchar(10),'
set @j=@j+1
end
set @sql=left(@sql,len(@sql)-1)+')'
set @sql=@sql+' insert #t select '''
set @sql1=''
select @sql1=@sql1+replace(col,'*',''',''')+ ''' union all select ''' from 表1
set @sql1=left(@sql1,len(@sql1)-18)+' select * from #t'
exec(@sql+@sql1)
--建立測試環境
Create Table Test(col varchar(100))
Insert Into Test(col) select '11*22*33*55*66'
Insert Into Test(col) select '22*33*44*32'
Insert Into Test(col) select '33*55'
Insert Into Test(col) select '44'
GO
--建立存儲過程
Create Procedure SP_Test
As
Begin
Declare @I Int,@J Int,@Col1 Varchar(20),@Col2 Varchar(20)
Declare @S Varchar(1000)
Set @J=1
Select @I=Max(Len(col)-Len(Replace(col,'*','')))+1 From Test
Set @S=''
While @J<=@I
Begin
Set @S=@S+'Alter Table TEST Add Col'+Rtrim(@J)+' Varchar(100);'
Set @J=@J+1
End
EXEC(@S)
EXEC('Update Test Set Col1=Col')
Set @J=2
While @@rowcount<>0 and @J<=@I
Begin
Select @Col1=Name From Syscolumns Where ID=OBJECT_ID('Test') and ColID=@J
Select @Col2=Name From Syscolumns Where ID=OBJECT_ID('Test') and ColID=@J+1
Set @S='Update Test Set '+@Col1+'= Left('+@col1+',Charindex(''*'','+@Col1+')-1)'
+','+@Col2+'=Stuff('+@Col1+',1,Charindex(''*'','+@Col1+'),'''')'
+' Where Charindex(''*'','+@Col1+')>0'
Set @J=@J+1
EXEC(@S)
End
End
GO
--測試
EXEC SP_Test
Select *From Test
GO
--刪除測試環境
Drop Table Test
Drop Procedure SP_Test
--結果
/*
Col Col1 Col2 Col3 Col4 Col5
11*22*33*55*66 11 22 33 55 66
22*33*44*32 22 33 44 32 NULL
33*55 33 55 NULL NULL NULL
44 44 NULL NULL NULL NULL