正版软件交易论坛

首页 » 资源专区 » 经典实例、教程! » 取得树结构中指点结点下的所有子结点,并可以返回树结点的层数
困了也不睡 - 2008-3-10 12:44:00
///取得树结构中指点结点下的所有子结点,并可以返回树结点的层数
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返回影响的记录数
1
查看完整版本: 取得树结构中指点结点下的所有子结点,并可以返回树结点的层数