sql 语句:根据父节点查找所有子节点

 set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER   function   f_id(@parentid  int)  
  returns   @re   table(orderid   int,parentid   int,title   nvarchar(50),level   int)  
  as  
  begin  
  declare   @l   int  
  set   @l=0  
  insert @re select @parentid,null,'',-1
  insert   @re   select   TabID,   ParentTabID   ,TabName,@l   from   rb_Tabs  
  where   ParentTabID=@parentid  
  while   @@rowcount>0  
  begin  
  set   @l=@l+1  
                  insert   into   @re   select    
                  a.TabID,a.ParentTabID,a.TabName,@l  
                  from   rb_Tabs   a,@re   b  
                  where   a.ParentTabID=b.orderid   and   b.level=@l-1  
  end  
  return  
  end  
  go  




使用方法:
declare @cat int
set @cat  = 406
SELECT
       rb_Products_st.ProductID,
   rb_Products_st.DisplayOrder,
   rb_Products_st.ModelNumber,
   rb_Products_st.ModelName,
   rb_Products_st.UnitPrice,
   rb_Products_st.FeaturedItem,
   rb_Products_st.LongDescription,
   rb_Products_st.ShortDescription,
   rb_Products_st.MetadataXml,
   rb_Products_st.Weight,
   rb_Products_st.TaxRate
  FROM
   rb_Products_st
  WHERE
      rb_Products_st.CategoryID in (select   orderid   from   dbo.f_id(@cat) )

posted @   Ready!  阅读(1122)  评论(1编辑  收藏  举报
编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· 对象命名为何需要避免'-er'和'-or'后缀
· JDK 24 发布,新特性解读!
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· SQL Server如何跟踪自动统计信息更新?
点击右上角即可分享
微信分享提示