create table tb(id int,parentid int,sname varchar(10))
insert into tb select 1 , -1 , '根节点'
insert into tb select 2 , 1 , '节点1'
insert into tb select 3 , 1 , '节点2'
insert into tb select 4 , 2 , '节点3'
insert into tb select 5 , 2 , '节点4'
insert into tb select 6 , 3 , '节点5'
insert into tb select 7 , 3 , '节点6'
insert into tb select 7 , 6 , '节点7'
go
CREATE FUNCTION f_Cid(@ID int)
RETURNS @t_Level TABLE(ID int,Level int)
AS
BEGIN
DECLARE @Level int
SET @Level=1
INSERT @t_Level SELECT @ID,@Level
WHILE @@ROWCOUNT>0
BEGIN
SET @Level=@Level+1
INSERT @t_Level SELECT a.ID,@Level
FROM tb a,@t_Level b
WHERE a.parentID=b.ID
AND b.Level=@Level-1
END
RETURN
END
GO
select distinct a.*
from f_cid(3) b ,tb a
where b.id=a.id
and not exists(select * from tb where parentid=b.id)
go
drop table tb
drop function f_cid
/*
id parentid sname
----------- ----------- ----------
7 3 节点6
7 6 节点7
(所影响的行数为 2 行)
*/