日期:2014-05-18  浏览次数:20488 次

问一个复杂的SQL解析的问题
table1   这张表有两个字段,字段名分别为   row1     row2
数据的形式是这样的:

row1             row2
1                   a,b,c,
2                   d,e,f,
3                   g,h,i


我想解析row2里的数据,转到一张新表table2(两个字段名为newrow1   newrow2)里,成这种方式:

newrow1           newrow2
1                       a
1                       b
1                       c
2                       d
2                       e
2                       f
3                       g
3                       h
3                       i

用SQL语句怎么写好呢?     数据量大概一万多条.

谢谢了!!

------解决方案--------------------
declare @a table(row1 int, row2 varchar(100))
insert @a select 1 , 'a,b,c '
union all select 2 , 'd,e,f '
union all select 3 , 'g,h,i '

select top 200 id=identity(int,1,1) into # from syscolumns a ,syscolumns b

select row1,substring(row2+ ', ',id,charindex( ', ',row2+ ', ',id+1)-id) b
from #,@a
where substring( ', '+row2,id,1)= ', '

drop table #
------解决方案--------------------
declare @t table(row1 int,row2 varchar(20))
insert into @t values(1, 'a,b,c, ')
insert into @t values(2, 'd,e,f, ')
insert into @t values(3, 'g,h,i ')

select
row1,
parseName(row2,3) as row2,
parseName(row2,2) as row3,
parseName(row2,1) as row4
from
(select row1,replace(case when right(row2,1)= ', ' then left(row2,len(row2)-1) else row2 end, ', ', '. ') as row2 from @t) t

/*
row1 row2 row3 row4
----------- ------------ ----------- -------------
1 a b c
2 d e f
3 g h i
*/

select
row1,
parseName(row2,3) as row2
from
(select row1,replace(case when right(row2,1)= ', ' then left(row2,len(row2)-1) else row2 end, ', ', '. ') as row2 from @t) t
union all
select
row1,
parseName(row2,2)
from
(select row1,replace(case when right(row2,1)= ', ' then left(row2,len(row2)-1) else row2 end, ', ', '. ') as row2 from @t) t
union all
select
row1,
parseName(row2,1)
from
(select row1,replace(case when right(row2,1)= ', ' then left(row2,len(row2)-1) else row2 end, ', ', '. ') as row2 from @t) t

/*
row1 row2
----------- ------------
1 a
2 d
3 g
1 b
2 e
3 h
1 c
2 f
3 i