日期:2014-05-18 浏览次数:20423 次
--生成测试数据 create table tTmp( id varchar(10), t2 varchar(100), t3 varchar(100), parentid varchar(10)) insert into tTmp select '1', '12','13','0' union all select '2', '22','23','1' union all select '3', '32','33','2' select * from tTmp /* id t2 t3 parentid 1 12 13 0 2 22 23 1 3 32 33 2 */ WITH cteTmp AS ( SELECT A.*, Convert(varchar(100),t2) as DetailName FROM tTmp AS A WHERE NOT EXISTS(SELECT * FROM tTmp WHERE id=A.parentid) UNION ALL SELECT A.*, Convert(varchar(100),(A.t2 + B.DetailName)) AS DetailName FROM tTmp AS A JOIN cteTmp AS B ON A.parentid=B.id ) SELECT id,t2,t3,parentid,DetailName+t3 as t2t3 FROM cteTmp order by DetailName; /* id t2 t3 parentid t2t3 1 12 13 0 1213 2 22 23 1 221223 3 32 33 2 32221233 */ select * from tTmp /* id t2 t3 parentid 1 12 13 0 2 22 23 1 3 32 33 2 */ WITH cteTmp AS ( SELECT A.*, Convert(varchar(100),t2) as DetailName FROM tTmp AS A WHERE NOT EXISTS(SELECT * FROM tTmp WHERE id=A.parentid) UNION ALL SELECT A.*, Convert(varchar(100),(A.t2 + B.DetailName)) AS DetailName FROM tTmp AS A JOIN cteTmp AS B ON A.parentid=B.id ) update tTmp set tTmp.t2 = (select cteTmp.DetailName from cteTmp where tTmp.id = cteTmp.id)+ tTmp.t3 select * from tTmp /* id t2 t3 parentid 1 1213 13 0 2 221223 23 1 3 32221233 33 2 */ drop table tTmp;