22,209
社区成员
发帖
与我相关
我的任务
分享
如果嵌套的层次不多的话,可以使用连接,直接写
update a
set a.id=case when b.id is null then a.pid else b.pid end
from tb a left join tb b on b.pid=a.id
select * from tb
456 456
456 789
234 234
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] varchar(3),[pid] varchar(3))
insert [tb]
select '123','456' union all
select '456','789' union all
select '012','234'
go
with cte as
(
select topid=pid,id,pid from tb a where not exists(select 1 from tb where id=a.pid)
union all
select c.topid,a.id,a.pid from tb a join cte c on a.pid=c.id
)
update tb
set id=cte.topid
from cte
where tb.pid=cte.pid
select * from [tb]
--测试结果:
/*
id pid
---- -----------
789 456
789 789
234 234
(3 行受影响)
*/
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] varchar(3),[pid] int)
insert [tb]
select '123',456 union all
select '456',789 union all
select '012',234
go
with cte as
(
select topid=pid,id,pid from tb a where not exists(select 1 from tb where id=a.pid)
union all
select c.topid,a.id,a.pid from tb a join cte c on a.pid=c.id
)
update tb
set id=cte.topid
from cte
where tb.pid=cte.pid
select * from [tb]
--测试结果:
/*
id pid
---- -----------
789 456
789 789
234 234
(3 行受影响)
*/
with cte as
(
select topid=pid,id,pid from tb a where not exists(select 1 from tb where id=a.pid)
union all
select c.topid,a.id,a.pid from tb a join cte c on a.pid=c.id
)
update tb
set id=cte.topid
from cte
where tb.pid=cte.pid