SQL 遞歸找查全部子節點及全部父節

在SQL的樹型結構中,不少時候,知道某一節點的值,須要查找該節點的全部子節點(包括多級)的功能,這時就須要用到以下的用戶自定義函數.函數

    表結構以下:spa

    

ID int
Dep_Type int
Dep_Code varchar(50)
Dep_Name varchar(50)
Dep_Dian int
Dep_FathID int
Dep_Opera varchar(50)
Dep_Status int
Dep_AddTime datetime

 

用戶自定義函數以下:ci

create function f_getChild(@ID VARCHAR(10)) 
returns @t table(ID VARCHAR(10),PID VARCHAR(10),Level INT) 
as 
begin 
    declare @i int,@ret varchar(8000) 
    set @i = 1 
    insert into @t select ID,Dep_FathID,@i from H_Dep_Info where Dep_FathID = @ID 
    while @@rowcount<>0 
    begin 
      set @i = @i + 1 
      insert into @t select a.ID,a.Dep_FathID,@i from H_Dep_Info a,@t b where a.Dep_FathID=b.ID and b.Level = @i-1 
    end 
    return 
endget

執行操做以下:io

select ID from f_getChild(1)table

返回值就是全部的子節點function

 

查找父節點的函數以下:date

CREATE FUNCTION [f_getParent](@id int) 
  RETURNS @re TABLE(id int,pid int,level int) 
  AS 
  begin 
  declare @level int 
  set @level = 1 
  declare @pid int 
  select @pid = pid from tb where id = @id 
  insert @re 
  select id,pid,@level from tb where id = @pid 
  while @@rowcount > 0   
  begin 
  set @level = @level + 1 
  select @pid = pid from tb where id = @pid 
  insert @re 
  select id,pid,@level from tb where id = @pid 
  end 
  return 
  endselect

 

執行操做以下:im

select * from f_getParent(8)

返回的列有id,pid,level

其中id就是8的父節點,pid就是id的父節點,level就是級數(表示這個id是8的第幾級你節點)

相關文章
相關標籤/搜索