Sql语句之递归查询
直接進入正題
比如一個表,有id和pId字段,id是主鍵,pid表示它的上級節點,表結構和數據:
?
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結點的所有子結點
with my1 as(select * from aaa where id = 1
?union all select aaa.* from my1, aaa where my1.id = aaa.pid
)
select * from my1 --結果包含1這條記錄,如果不想包含,可以在最后加上:where id <> 1
--下面的Sql是查詢出8結點的所有父結點
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結點和所有子結點的語句:
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使用表達式遞歸查詢
--由父項遞歸下級 
with cte(id,parentid,text) 
as 
(--父項 
select id,parentid,text from treeview where parentid = 450 
union all 
--遞歸結果集中的下級 
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 
--由子級遞歸父項 
with cte(id,parentid,text) 
as 
(--下級父項 
select id,parentid,text from treeview where id = 450 
union all 
--遞歸結果集中的父項 
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
?
?
轉載于:https://www.cnblogs.com/ckblogs/p/3679787.html
總結
以上是生活随笔為你收集整理的Sql语句之递归查询的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: for in / for of 要会用
- 下一篇: BT1120,模拟视频输入输出格式
