///取得树结构中指点结点下的所有子结点,并可以返回树结点的层数
create function f_id(
@FID int
)returns @re table(FID int,level int)
as
begin
declare @l int
set @l=0
insert @re select @FID,@l
while @@rowcount>0
begin
set @l=@l+1
insert @re select a.FID,@l
from test a,@re b
where a.FParentID=b.FID
and
b.level=@l-1 end
return
end
调用方法:select a.*,b.level
from test a,f_id(10) b
where a.FID=b.FID
表结构:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[test]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[test]
GO
CREATE TABLE [dbo].[test] (
[fid] [bigint] IDENTITY (1, 1) NOT NULL ,
[FParentID] [bigint] NULL ,
[name] [char] (10) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
说明:
@@rowcount返回影响的记录数