日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Sql语句之递归查询

發布時間:2023/12/10 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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语句之递归查询的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。