sql遞迴查詢

2021-08-10 18:43:22 字數 1688 閱讀 8323

--有兩個表,a 部門表,儲存部門id 名稱 上級部門;b表 儲存部門員工表 id 姓名 部門id

--現在我希望通過一條sql語句取得所有頂級部門下的員工(包含下級部門的員工)

--drop table dept;

create table dept(

dept_id varchar(5),

up_id varchar(5),

misc varchar(20),

primary key (dept_id)

);insert into dept (dept_id, up_id, misc) values ('12', '-', '頂級部門2');

insert into dept (dept_id, up_id, misc) values ('1', '-', '頂級部門');

insert into dept (dept_id, up_id, misc) values ('01', '1', '部門1');

insert into dept (dept_id, up_id, misc) values ('02', '1', '部門2');

insert into dept (dept_id, up_id, misc) values ('003', '02', '部門3');

--drop table employ;

create table employ(

emp_id varchar(6),

name varchar(20),

dept_id varchar(5),

primary key(emp_id)

);insert into employ (emp_id, name, dept_id) values ('00001', '錢八', '1');

insert into employ (emp_id, name, dept_id) values ('00002', '趙六', '01');

insert into employ (emp_id, name, dept_id) values ('00003', '王五', '02');

insert into employ (emp_id, name, dept_id) values ('00004', '李四', '02');

insert into employ (emp_id, name, dept_id) values ('00005', '張三', '003');

--查詢部門為1-頂級部門下的所有員工

with temp(emp_id,name,dept_id) as (

select e.emp_id,e.name,e.dept_id from employ e left join dept d on e.dept_id = d.dept_id where e.dept_id = '1'

union all

select d2.emp_id,d2.name,d2.dept_id from temp t,

( select emp_id,name,e.dept_id,d3.up_id from employ e,dept d3 where e.dept_id = d3.dept_id)d2 where t.dept_id = d2.up_id

)select distinct(emp_id),name,dept_id from temp order by emp_id;

遞迴查詢SQL

lz需要的修改自己為對應的,csdn sqlserve大版主 鄒建 我轉貼並且完善一下 測試資料 create table tb id char 3 pid char 3 name nvarchar 10 insert tb select 001 null 山東省 union all select ...

SQL遞迴查詢

create table t bid int,p bid int insert into t select 1,null union all select 2,1 union all select 3,1 union all select 4,3 union all select 5,4 union...

SQL 遞迴查詢

create proc proc tree node int asbegin declare i int set i 0 set nocount on drop table res create table res node int,child int,weight int,op int inser...