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

 

/*--   得到指定id的父id列表   --*/  
  --不包含排序字段的情况  
  create   function   f_getparentid(@id   int)  
  returns   @re   table(id   int)  
  as  
  begin  
  declare   @pid   int  
  select   @pid=pid   from   tb   where   id=@id  
  while   @pid<>0  
  begin  
  insert   into   @re   values(@pid)  
  select   @pid=pid   from   tb   where   id=@pid  
  end  
  return  
  end  
  go  
   
  --包含排序字段的情况  
  create   function   f_getparentidsort(@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  
   
  declare   @pid   int,@sortid   varchar(8000)  
  select   @pid=pid,@sortid=right(@idheader+cast(pid   as   varchar),@idlen)  
  from   tb   where   id=@id  
  while   @pid<>0  
  begin  
  insert   into   @re values(@pid,@sortid)  
  select   @pid=pid,@sortid=right(@idheader+cast(pid   as   varchar),@idlen)  
  from   tb   where   id=@pid  
  end  
  return  
  end  
  go  
   
  --调用示例,显示9的所有父  
  select   a.*   from   tb   a   inner   join   dbo.f_getparentidsort(9)   b   on   a.id=b.id   order   by   b.sortid  

相关文章:

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