天天看點

SQL server 樹形遞歸查詢

1,原始查詢

select * from dbo.T_DeptInfo;

原始表格查詢結果:

SQL server 樹形遞歸查詢

2,遞歸查詢

-- with 一個臨時表(括号裡包括的是你要查詢的列名)
with tem_table(dept_id,parent_id,dep_name,curlevel)
as
(
--1,初始查詢(這裡的parent_id='000'是我門資料中最底層的根節點)
select   dept_id, parent_dept_id, dept_name, 1 as level 
     from 
           dbo.T_DeptInfo 
     where 
           parent_dept_id = '000'
union all
--2,遞歸條件
select   a.dept_id,  a.parent_dept_id,  a.dept_name, b.curlevel+1                          
    from 
         dbo.T_DeptInfo  a 
    inner join 
         tem_table  b
    on (a.parent_dept_id = b.dept_id)
)
select * from tem_table;  --3,遞歸完成後,一定不能少了這句查詢語句,否則會報錯

           

遞歸查詢結果

SQL server 樹形遞歸查詢

3,帶縮進的的樹形遞歸查詢

-- with 一個臨時表(括号裡包括的是你要查詢的列名)
with tem_table(dept_id,parent_id,dep_name,curlevel)
as
(
--1,初始查詢(這裡的parent_id='000'是我門資料中最底層的根節點)
select   dept_id, parent_dept_id, dept_name, 1 as level 
     from 
           dbo.T_DeptInfo 
     where 
           parent_dept_id = '000'
union all
--2,遞歸條件
select   a.dept_id,  a.parent_dept_id, 
         convert(varchar(100),convert(varchar(100),replicate('    ',b.curlevel+1) + a.dept_name )) as dept_name ,
         b.curlevel+1                          
    from 
         dbo.T_DeptInfo  a 
    inner join 
         tem_table  b
    on (a.parent_dept_id = b.dept_id)
)
select * from tem_table;  --3,遞歸完成後,一定不能少了這句查詢語句,否則會報錯
           

縮進遞歸查詢結果

SQL server 樹形遞歸查詢

4,查詢是否子節點的樹形遞歸查詢

-- with 一個臨時表(括号裡包括的是你要查詢的列名)
with tem_table(dept_id,parent_id,dep_name,curlevel,havechild)
as
(
--1,初始查詢(這裡的parent_id='000'是我門資料中最底層的根節點)
select   dept_id, parent_dept_id, dept_name, 1 as level,1 as havechild 
     from 
           dbo.T_DeptInfo 
     where 
           parent_dept_id = '000'
union all
--2,遞歸條件
select   a.dept_id,  a.parent_dept_id,  a.dept_name, b.curlevel+1,
         havechild =(
              case 
                 when exists(select 1 from T_DeptInfo where T_DeptInfo.parent_dept_id = a.dept_id ) then 1
                 else  0
              end
         )                          
    from 
         dbo.T_DeptInfo  a 
    inner join 
         tem_table  b
    on (a.parent_dept_id = b.dept_id)
)
select * from tem_table;  --3,遞歸完成後,一定不能少了這句查詢語句,否則會報錯
           

樹形遞歸查詢是否包含子節點的查詢結果

SQL server 樹形遞歸查詢