|
create table 表(ID int,是否為部門 char(1),部門名 varchar(10),上級ID int)
insert 表 select 1 , 'y ', '部門0 ' ,1
union all select 31, 'y ', '部門1 ' ,1
union all select 32, 'n ', '張三 ' ,31
union all select 33, 'n ', '李二 ' ,31
union all select 34, 'y ', '部門2 ',31
union all select 35, 'n ', '王五 ' ,34
union all select 35, 'y ', '部門3 ',34
union all select 36, 'n ', '小三 ' ,35
go
--建立查詢函數
create function f_id(
@id int --要查詢的id
)returns @re table(id int,level int)
as
begin
declare @l int
set @l=0
insert @re select id,@l
from 表
where 上級id=@id
while @@rowcount> 0
begin
set @l=@l+1
insert @re select a.id,@l
from 表 a join @re b on a.上級id=b.id and b.level=@l-1
end
return
end
go
--調用函數進行查詢
select a.* from 表 a join f_id(35) b on a.id=b.id
go
--刪除測試
drop table 表
drop function f_id
/*--測試結果
ID 是否為部門 部門名 上級ID
----------- ----- ---------- -----------
36 n 小三 35
(所影響的行數為 1 行)
--*/ |