日期:2014-05-17  浏览次数:20437 次

sql 字符串行转成列
本帖最后由 terry2018 于 2012-11-25 00:26:17 编辑 源数据:

oneId       cIdStr
----------- ----------------------------------------------------------------------------------------------------------------
1           88,37,35,89,37,35
2           52,49



-----------------------------------
要得到的数据:

oneId       cIdStr
----------- ----------------------------------------------------------------------------------------------------------------
1           88
1           37
1           35
1           89
1           37
1           35
2           52
2           49


该如何实现?各位大侠
------最佳解决方案--------------------
sample:
create table tb(watch_date datetime,dangwei nvarchar(20),zhihui nvarchar(30),jiguan nvarchar(30),xingzhen nvarchar(30))
insert into tb select '2009-2-3','张朝娜','叶长勇','关炜 万慧阳 李中明 余茂菲 李金键','王照华 陈开义 志勇'
insert into tb select '2009-2-4','aaa','bbb ccc','ddd eee','fff kkk'
go
select * into # from(
select watch_date,dangwei as watch from tb
union all
select watch_date,zhihui as watch from tb
union all
select watch_date,jiguan as watch from tb
union all
select watch_date,xingzhen as watch from tb
)T
;
with cte as(
select watch_date,convert(varchar,watch)as watch,convert(varchar(30),'') as flg from # where charindex(' ',watch)=0
union all
select watch_date,convert(varchar,left(watch,charindex(' ',watch))) as watch,right(watch,len(watch)-charindex(' ',watch))+' ' as flg from # where charindex(' ',watch)>1
union all
select watch_date,convert(varchar,left(flg,charindex(' ',flg))) as watch,right(flg,len(flg)-charindex(' ',flg)+1) as flg from cte where charindex(' ',flg)>1
)select watch_date,watch from cte order by watch_date
go
drop table tb,#
/*
watch_date              watch
----------------------- ------------------------------
2009-02-03 00:00:00.000 张朝娜
2009-02-03 00:00:00.000 叶长勇
2009-02-03 00:00:00.000 关炜 
2009-02-03 00:00:00.000 王照华 
2009-02-03 00:00:00.000 万慧阳 
2009-02-03 00:00:00.000 李中明 
2009-02-03 00:00:00.000 余茂菲 
2009-02-03 00:00:00.000 李金键