日期:2014-05-17 浏览次数:20534 次
if object_id('[tb]') is not null drop table [tb]
go
create table [tb](A varchar(40),B varchar(10))
insert [tb]
select 'a/a/c','x' union all
select 'a/b/c','x'
go
if OBJECT_ID('tempdb..#temp1') is not null
drop table #temp1
if OBJECT_ID('tempdb..#temp2') is not null
drop table #temp2
select *,IDENTITY(int,1,1) id into #temp1
from tb
declare @sql nvarchar(4000)
set @sql = '';
;with t
as
(
select ID,
SUBSTRING(t.A, number ,CHARINDEX('/',t.a+'/',number)-number) as v,
b,
row_number() over(partition by id order by @@servername) as rownum
from #temp1 t,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING('/'+t.A,s.number,1) = '/'
)
select * into #temp2
from t
select @sql = @sql + ',max(case when rownum = '+CAST(rownum as varchar)+
' then v else null end) as 列'+CAST(rownum as varchar)
from #temp2
group by rownum
set @sql = 'select '+STUFF(@sql,1,1,'')+ ',b' +
' from #temp2 group by id,b'
--select @sql
exec(@sql)
/*
列1 列2 列3 b
a a c x
a b c x
*/