SQL Server 通過with as方法查詢樹型結(jié)構(gòu)
一、with as 公用表表達(dá)式
類似VIEW,但是不并沒有創(chuàng)建對(duì)象,WITH AS 公用表表達(dá)式不創(chuàng)建對(duì)象,只能被后隨的SELECT語句,其作用:
1. 實(shí)現(xiàn)遞歸查詢(樹形結(jié)構(gòu))
2. 可以在一個(gè)語句中多次引用公用表表達(dá)式,使其更加簡(jiǎn)潔
二、非遞歸的公共表達(dá)式
可以是定義列或自動(dòng)列和select into 效果差不多
--指定列 with withTmp1 (code,cName) as ( select id,Name from ClassUnis ) select * from withTmp1 --自動(dòng)列 with withTmp2 as ( select * from ClassUnis where Author = 'system' ) select * from withTmp2
三、遞歸的方式
通過UNION ALL 連接部分。通過連接自身whit as 創(chuàng)建的表達(dá)式,它的連接條件就是遞歸的條件??梢詮母?jié)點(diǎn)往下查找,從子節(jié)點(diǎn)往父節(jié)點(diǎn)查找。只需要顛倒一下連接條件。例如代碼中條件改為t.ID = c.ParentId即可
with tree as( --0 as Level 定義樹的層級(jí),從0開始 select *,0 as Level from ClassUnis where ParentId is null union all --t.Level + 1每遞歸一次層級(jí)遞增 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) 設(shè)置最大遞歸次數(shù)。例如上訴結(jié)果Level 最大值為2表示遞歸兩次。我們?cè)O(shè)置其值為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)
好了這篇文章就介紹到這了,希望能幫助到你。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。