共計 1212 個字符,預計需要花費 4 分鐘才能閱讀完成。
SQL Server 如何通過 with as 方法查詢樹型結構,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
一、with as 公用表表達式
類似 VIEW,但是不并沒有創建對象,WITH AS 公用表表達式不創建對象,只能被后隨的 SELECT 語句,其作用:
1. 實現遞歸查詢 (樹形結構)
2. 可以在一個語句中多次引用公用表表達式,使其更加簡潔
二、非遞歸的公共表達式
可以是定義列或自動列和 select into 效果差不多
-- 指定列 with withTmp1 (code,cName)as( select id,Name from ClassUnis)select * from withTmp1-- 自動列 with withTmp2 as( select * from ClassUnis where Author = system)select * from withTmp2
三、遞歸的方式
通過 UNION ALL 連接部分。通過連接自身 whit as 創建的表達式,它的連接條件就是遞歸的條件。可以從根節點往下查找,從子節點往父節點查找。只需要顛倒一下連接條件。例如代碼中條件改為 t.ID = c.ParentId 即可
with tree as( --0 as Level 定義樹的層級, 從 0 開始 select *,0 as Level from ClassUnis where ParentId is null union all --t.Level + 1 每遞歸一次層級遞增 select c.*,t.Level + 1 from ClassUnis c,tree t where c.ParentId = t.ID --from ClassUnis c inner join tree t on c.ParentId = t.ID)select * from tree where Author not like %/%
還能通過 option(maxrecursion Number) 設置最大遞歸次數。例如上訴結果 Level 最大值為 2 表示遞歸兩次。我們設置其值為 1
with tree as( select *,0 as Level from ClassUnis where ParentId is null union all select c.*,t.Level + 1 from ClassUnis c,tree t where c.ParentId = t.ID)select * from tree where Author not like %/% option(maxrecursion 1)
關于 SQL Server 如何通過 with as 方法查詢樹型結構問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注丸趣 TV 行業資訊頻道了解更多相關知識。
正文完