--数据结构   
  表名tb,如果修改表名,则相应修改所有数据处理中涉及到的表名tb  
  id为编号(标识字段+主键)  
  pid为上级编号  
  name为名称,后面可以自行增加其他字段.

 

/*--   得到指定id的子id列表   --*/  
  --不包含排序字段的情况  
  create   function   f_getchildid(@id   int)  
  returns   @re   table(id   int)  
  as  
  begin  
  insert   into   @re   select   id   from   tb   where   pid=@id  
  while   @@rowcount>0  
  insert   into   @re select   a.id    
  from   tb   a   inner   join   @re   b   on   a.pid=b.id  
  where   a.id   not   in(select   id   from   @re)  
  return  
  end  
  go  
   
  --包含排序字段的情况  
  create   function   f_getchildidsort(@id   int)  
  returns   @re   table(id   int,sortid   varchar(8000))  
  as  
  begin  
  --为了数字排序正常,需要统一编码宽度  
  declare   @idlen   int,@idheader   varchar(20)  
  select   @idlen=max(len(id))  
  ,@idheader=space(@idlen)  
  from   tb  
   
  insert   into   @re   select   id,right(@idheader+cast(id   as   varchar),@idlen)  
  from   tb   where   pid=@id  
  while   @@rowcount>0  
  insert   into   @re select   a.id,right(@idheader+cast(a.id   as   varchar),@idlen)+','+b.sortid    
  from   tb   a   inner   join   @re   b   on   a.pid=b.id  
  where   a.id   not   in(select   id   from   @re)  
  return  
  end  
  go  
   
  --调用示例,显示1的所有子.  
  select   a.*   from   tb   a   inner   join   dbo.f_getchildidsort(1)   b   on   a.id=b.id   order   by   b.sortid  

相关文章:

  • 2022-01-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-09
  • 2022-12-23
  • 2022-02-19
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-02-20
  • 2022-12-23
  • 2022-12-23
  • 2021-03-27
  • 2022-03-11
相关资源
相似解决方案