• SQLServer递归的问题用存储过程实现[32層限制]


    表结构:  
    T_Master:  
    Bh  bigint(8)  PK                    //节点编号  
    Label  varchar(50)                //节点名称  
    ParentBh  bigint(8)              //父节点编号  
     
    由这个表建的一个棵树结构,层次用节点编号和父节点编号控制  
     
    我想写一个存储过程,传入一个任意节点的编号,返回该节点下所有节点的表。  
     
    不知可否实现?  
    谢谢!  
     
     
    ---------------------------------------------------------------  
     
    oops,  sorry,  switch  insert  and  set:  
     
    select  *  into  temptable  from  T_Master  where  1  =  2  
     
    alter  table  temptable  add  depth  int    
    go  
     
    declare  @node  bigint  
    declare  @depth  int  
     
    set  @node  =  123  --指定节点编号  
    set  @depth  =  1  
     
    insert  into  temptable  select  *,  @depth  from  T_Master  Where  ParentBh  =  @node  
     
    while  @@ROWCOUNT  >  0  
    begin  
       set  @depth  =  @depth  +  1  
     
       insert  into  temptable    
       select  *,  @depth  
       from  T_Master  Where  ParentBh  in  (select  Bh  from  temptable  WHERE  depth=@depth-1)  
         
    end    
     
     
    select  *  from  temptable  
     
    drop  table  temptable  
     
    ---------------------------------------------------------------  
     
    这样:  
     
    declare  @a  table  (TC_Id  int,TC_PID  int,TC_Name  varchar(200))  
    insert  @a  values(1,0,'中国')  
    insert  @a  values(2,0,'美国')  
    insert  @a  values(3,0,'加拿大')  
    insert  @a  values(4,1,'北京')  
    insert  @a  values(5,1,'上海')  
    insert  @a  values(6,1,'江苏')  
    insert  @a  values(7,6,'苏州')  
    insert  @a  values(8,7,'常熟')  
    insert  @a  values(9,6,'南京')  
    insert  @a  values(10,6,'无锡')  
    insert  @a  values(11,2,'纽约')  
    insert  @a  values(12,2,'旧金山')  
     
    declare  @tmp1  table  (TC_Id  int,TC_PID  int,TC_Name  varchar(200),lev  int)  
    insert  @tmp1  select  *,1  from  @a  where  tc_ID=1  
    while  exists(select  1  from  @a  a,@tmp1  b  where  a.tc_pid=b.tc_ID  and  a.tc_ID  not  in  (select  tc_ID  from  @tmp1))  
       insert  @tmp1  select  a.*,1  from    @a  a,@tmp1  b  where  a.tc_pid=b.tc_ID  and  a.tc_ID  not  in  (select  tc_ID  from  @tmp1)  
    select  *  from  @tmp1
  • 相关阅读:
    centos6 vps部署rails
    初始设置ubuntu 16.04 Vps部署rails
    自己买的书籍
    linux mint 18.2 install erlang
    Bunder: What does :require => nil in Gemfile mean?
    javascript箭头函数
    SharpGL学习笔记(一) 平台构建与Opengl的hello World
    动力学仿真引擎ODE的学习笔记,C#演示(一)
    设计模式之 面向对象的养猪厂的故事,C#演示(二)
    设计模式之 面向对象的养猪厂的故事,C#演示(一)
  • 原文地址:https://www.cnblogs.com/godwar/p/1047443.html
Copyright © 2020-2023  润新知