zoukankan      html  css  js  c++  java
  • 有关树的运用和存储过程.txt

    --建立測試環境
    Create Table department
    (departmenid Int,
    parentid Int)
    Insert department Select 60, null
    Union All Select 1, 0
    Union All Select 2, 1
    Union All Select 3, 1
    Union All Select 4, 2
    Union All Select 5, 2
    Union All Select 6, 3
    Union All Select 7, 3
    Union All Select 8, 7
    GO
    --建立函數
    Create Function F_GetParent(@departmenid Int)
    Returns @Tree Table (departmenid Int, parentid Int)
    As
    Begin
    Insert @Tree Select * From department Where departmenid = @departmenid
    While @@Rowcount > 0
    Insert @Tree Select A.* From department A Inner Join @Tree B On A.departmenid = B.parentid And A.departmenid Not In (Select departmenid From @Tree) Where A.parentid Is Not Null
    Return
    End
    GO
    --測試
    Select departmenid From dbo.F_GetParent(8) Order By parentid
    GO
    --刪除測試環境
    Drop Table department
    Drop Function F_GetParent
    --結果
    /*
    departmenid
    1
    3
    7
    8
    */

    --建立測試環境
    Create Table department
    (departmenid Int,
    parentid Int)
    Insert department Select 60, null
    Union All Select 1, 0
    Union All Select 2, 1
    Union All Select 3, 1
    Union All Select 4, 2
    Union All Select 5, 2
    Union All Select 6, 3
    Union All Select 7, 3
    Union All Select 8, 7
    GO
    --創建存儲過程
    Create ProceDure SP_GetParent(@departmenid Int)
    As
    Begin
    Select * Into #Tree From department Where departmenid = @departmenid
    While @@Rowcount > 0
    Insert #Tree Select A.* From department A Inner Join #Tree B On A.departmenid = B.parentid And A.departmenid Not In (Select departmenid From #Tree) Where A.parentid Is Not Null
    Select departmenid From #Tree Order By parentid
    Drop Table #Tree
    End
    GO
    --測試
    EXEC SP_GetParent 8
    GO
    --刪除測試環境
    Drop Table department
    Drop ProceDure SP_GetParent
    --結果
    /*
    departmenid
    1
    3
    7
    8
    */

  • 相关阅读:
    OCP-1Z0-053-200题-36题-615
    Android换行符变成方框的解决方法
    OCP-1Z0-053-200题-35题-614
    FusionCharts 3D帕累托图
    FusionCharts 3D帕累托图报错
    FusionCharts 2D帕累托图
    OCP-1Z0-053-200题-33题-612
    OCP-1Z0-053-V13.02-612题
    OCP-1Z0-053-200题-32题-611
    OCP-1Z0-053-V13.02-611题
  • 原文地址:https://www.cnblogs.com/shihao/p/2511095.html
Copyright © 2011-2022 走看看