34,588
社区成员
发帖
与我相关
我的任务
分享
CREATE TABLE aaa (
colA VARCHAR(30),
colB VARCHAR(30)
)
insert into aaa values
('A','B'),('B','C'),('C','D'),('D','E'),
('1','2'),('2','3'),('3','4')
go
with m as (
select 0 as id, t.colA, t.colB, t.colB leaf_colB
from aaa t where colB in('E','4')
union all
select m.id + 1 , t.colA, t.colB, m.leaf_colB
from aaa t,m where m.colA = t.colB
)
select * from m
where not exists(select * from m a where m.leaf_colB = leaf_colB and id> m.id)
go
drop table aaa
go
(7 行受影响)
id colA colB leaf_colB
----------- -------------------- -------------------- ----------
2 1 2 4
3 A B E
(2 行受影响)
CREATE TABLE aaa (
colA VARCHAR(30),
colB VARCHAR(30)
)
insert into aaa values
('A','B'),('B','C'),('C','D'),('D','E'),
('1','2'),('2','3'),('3','4')
go
with m as (
select 0 as id, t.colA, t.colB from aaa t where colB ='E' -- '4'
union all
select m.id + 1 , t.colA, t.colB from aaa t,m where m.colA = t.colB
)
select top 1 * from m order by id desc
go
drop table aaa
go
(7 行受影响)
id colA colB
----------- ------------------------------ ------------------------------
3 A B
(1 行受影响)