|
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 alter 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 delete a from @t_level a where exists(select 1 from @t_level where a.level <level) RETURN END GO select a.* from f_cid(3) b ,tb a where b.id=a.id go drop table tb drop function f_cid 有理
|