日期:2014-05-18 浏览次数:20620 次
IF OBJECT_ID('tb') IS NOT NULL DROP TABLE tb; GO CREATE TABLE tb ( id INT identity(1,1), vt VARCHAR(500) ); GO INSERT INTO tb(vt) VALUES('1,2ab,c3,4eft'); INSERT INTO tb(vt) VALUES('1a,3,B'); select * from tb;
--分拆列值 --原著:邹建 --改编:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开) 2007-12-16 广东深圳 /* 有表tb, 如下: id value ----------- ----------- 1 aa,bb 2 aaa,bbb,ccc */ --欲按id,分拆value列, 分拆后结果如下: /* id value ----------- -------- 1 aa 1 bb 2 aaa 2 bbb 2 ccc */ --1. 旧的解决方法(sql server 2000) select top 8000 id = identity(int, 1, 1) into # from syscolumns a, syscolumns b select A.id, substring(A.[values], B.id, charindex(',', A.[values] + ',', B.id) - B.id) from tb A, # B where substring(',' + A.[values], B.id, 1) = ',' drop table # --2. 新的解决方法(sql server 2005) create table tb(id int,value varchar(30)) insert into tb values(1,'aa,bb') insert into tb values(2,'aaa,bbb,ccc') go select A.id, B.value from( select id, [value] = convert(xml,' <root> <v>' + replace([value], ',', ' </v> <v>') + ' </v> </root>') from tb )A outer apply( select value = N.v.value('.', 'varchar(100)') from A.[value].nodes('/root/v') N(v) )B drop table tb /* id value ----------- ------------------------------ 1 aa 1 bb 2 aaa 2 bbb 2 ccc (5 行受影响) */
------解决方案--------------------
-- 用with语句 ;with t as( select id, vt=(case when charindex(',',vt)>0 then substring(vt, charindex(',',vt)+1, len(vt)) else '' end), st=(case when charindex(',',vt)>0 then left(vt, charindex(',',vt)-1) else vt end) from tb union all select t.id, vt=(case when charindex(',',t.vt)>0 then substring(t.vt, charindex(',',t.vt)+1, len(t.vt)) else '' end), st=(case when charindex(',',t.vt)>0 then left(t.vt, charindex(',',t.vt)-1) else t.vt end) from t where len(t.vt)>0 ) select id, st from t order by id