## Welcome to itblog

Every Day In Every Way I Am Getting Better And Better~

# 一列拆分为多列

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

#### sql--一列拆分为多列

2007-07-17 15:07:00

#### Sql Server根据条件将一列拆分成多列

2015-06-22 18:50:47

#### 将表中一个字段拆分成多列 oracle db2字段拆分

2014-09-17 11:38:47

#### Oracle将一列分成多列

2015-05-11 23:50:59

#### Pandas: 如何将一列中的文本拆分为多行？

2018-05-21 13:20:26

#### 一列拆分为多列

2007-07-12 22:07:00

#### hive一行数据中一列拆分成多行

2015-03-27 15:28:37

#### 【数据平台】pandas将一列中的文本拆分成多行

2017-10-31 17:10:46

#### mysql把表中某一字段拆分为多列

2017-12-12 16:43:45

#### 【数据平台】dataframe一列成多列

2017-11-21 19:36:25