SQL數據庫實現遞歸查詢的幾種代碼方法
表結構
ProductCategory
CategoryID
數據
T
WITH CategoryTemp(CategoryID
(
SELECT CategoryID
UNION ALL
SELECT pc
LEFT JOIN CategoryTemp ct ON pc
WHERE ParentCategoryID>
)
SELECT CategoryID
結果
如果把ParentCategoryID賦為
實例
ID 是否為部門 部門名 上級ID
我想找詢 ID 值為
create function f_id(
@id int
)returns @re table(id int
as
begin
declare @l int
set @l=
insert @re select id
from 表
where 上級id=@id
while @@rowcount>
begin
set @l=@l+
insert @re select a
from 表 a join @re b on a
end
return
end
go
select a
聯合查詢
create table 表(ID int
insert 表 select
union all select
union all select
union all select
union all select
union all select
union all select
union all select
go
create function f_id(
@id int
)returns @re table(id int
as
begin
declare @l int
set @l=
insert @re select id
from 表
where 上級id=@id
while @@rowcount>
begin
set @l=@l+
insert @re select a
from 表 a join @re b on a
end
return
end
go
select a
go
drop table 表
drop function f_id
/*
ID 是否為部門 部門名 上級ID
(所影響的行數為
From:http://tw.wingwit.com/Article/program/MySQL/201311/29557.html