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)

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM