# 一列拆分为多列

11*22*33
22*33*44
33*55
44

11 22 33
22 33 44
33 55 NULL
44 NULL NULL

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

• 本文已收录于以下专栏：

举报原因： 您举报文章：一列拆分为多列 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)