--1.最后一层
select 子料
from 表
where 子料 not in (select 父料 from 表)--2.倒数第二层
select 子料
from 表
where 父料 in
(select 子料
from 表
where 子料 not in (select 父料 from 表))
select 子料
from 表
where 子料 not in (select 父料 from 表)--2.倒数第二层
select 子料
from 表
where 父料 in
(select 子料
from 表
where 子料 not in (select 父料 from 表))
(
[父料号] varchar(10),
[子料号] varchar(10)
)
insert A
select 'A1','A2' union
select 'A2','A3' union
select 'A3','A4' union
select 'B1','B2' union
select 'B2','B3'
go/*
获取最后两个子节点
*/
create function f_getLastTwoChildren(@parent varchar(10))
returns @tb table(ID int identity,
[父料号] varchar(10),
[子料号] varchar(10))
as
begin
insert @tb([父料号],[子料号])
select * from A where [父料号]=@parent while @@rowcount>0
begin
insert @tb([父料号],[子料号])
select A.*
from A
join @tb B on A.[父料号]=B.[子料号]
where A.[父料号] not in(select [父料号] from @tb)
end delete t
from @tb t
where (select count(1) from @tb where ID>=t.ID)>2 return
end
go--测试
select * from f_getLastTwoChildren('A1')
select * from f_getLastTwoChildren('B1')
--删除测试环境
drop function f_getLastTwoChildren
drop table A--结果
/*
ID 父料号 子料号
----------- ---------- ----------
2 A2 A3
3 A3 A4(2 row(s) affected)ID 父料号 子料号
----------- ---------- ----------
1 B1 B2
2 B2 B3(2 row(s) affected)
*/