请教递归更新问题,请大家帮忙!!

zhangzs8896 2008-11-18 09:36:17
有一表TB,内容如下:
子 父
123 456
456 789
012 234

也就是说123的父节点是456,456的父节点789.012的父节点是234
我想得到这样的结果:

子 父
789 456
789 789
234 234


也就是把子列的值更改为最终父节点的值.
谢谢!
...全文
80 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

如果嵌套的层次不多的话,可以使用连接,直接写

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
等不到来世 2008-11-18
  • 打赏
  • 举报
回复
pid类型换一下,无大碍
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 行受影响)
*/
等不到来世 2008-11-18
  • 打赏
  • 举报
回复
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 行受影响)
*/
等不到来世 2008-11-18
  • 打赏
  • 举报
回复

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
zhangzs8896 2008-11-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 CN_SQL 的回复:]
2000还是2005?
[/Quote]
是SQL2005
zhangzs8896 2008-11-18
  • 打赏
  • 举报
回复
是SQL2005
zhangzs8896 2008-11-18
  • 打赏
  • 举报
回复
2005
CN_SQL 2008-11-18
  • 打赏
  • 举报
回复
2000还是2005?

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧