Sql语句之递归查询
直接進(jìn)入正題
比如一個(gè)表,有id和pId字段,id是主鍵,pid表示它的上級(jí)節(jié)點(diǎn),表結(jié)構(gòu)和數(shù)據(jù):
?
CREATE TABLE [aaa](
?[id] [int] NULL,
?[pid] [int] NULL,
?[name] [nchar](10)
)
GO
INSERT INTO aaa VALUES(1,0,'a')
INSERT INTO aaa VALUES(2,0,'b')
INSERT INTO aaa VALUES(3,1,'c')
INSERT INTO aaa VALUES(4,1,'d')
INSERT INTO aaa VALUES(5,2,'e')
INSERT INTO aaa VALUES(6,3,'f')
INSERT INTO aaa VALUES(7,3,'g')
INSERT INTO aaa VALUES(8,4,'h')
GO
--下面的Sql是查詢出1結(jié)點(diǎn)的所有子結(jié)點(diǎn)
with my1 as(select * from aaa where id = 1
?union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
select * from my1 --結(jié)果包含1這條記錄,如果不想包含,可以在最后加上:where id <> 1
--下面的Sql是查詢出8結(jié)點(diǎn)的所有父結(jié)點(diǎn)
with my1 as(select * from aaa where id = 8
?union all select aaa.* from my1, aaa where my1.pid = aaa.id
)
select * from my1;
?--下面是遞歸刪除1結(jié)點(diǎn)和所有子結(jié)點(diǎn)的語句:
with my1 as(select * from aaa where id = 1
?? union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
delete from aaa where exists (select id from my1 where my1.id = aaa.id)
二:
SQLserver2008使用表達(dá)式遞歸查詢
--由父項(xiàng)遞歸下級(jí)
with cte(id,parentid,text)
as
(--父項(xiàng)
select id,parentid,text from treeview where parentid = 450
union all
--遞歸結(jié)果集中的下級(jí)
select t.id,t.parentid,t.text from treeview as t
inner join cte as c on t.parentid = c.id
)
select id,parentid,text from cte
--由子級(jí)遞歸父項(xiàng)
with cte(id,parentid,text)
as
(--下級(jí)父項(xiàng)
select id,parentid,text from treeview where id = 450
union all
--遞歸結(jié)果集中的父項(xiàng)
select t.id,t.parentid,t.text from treeview as t
inner join cte as c on t.id = c.parentid
)
select id,parentid,text from cte
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/ckblogs/p/3679787.html
總結(jié)
以上是生活随笔為你收集整理的Sql语句之递归查询的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: for in / for of 要会用
- 下一篇: BT1120,模拟视频输入输出格式