雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

MsSql

當(dāng)前位置:主頁 > 數(shù)據(jù)庫 > MsSql >

SQL Server 通過with as方法查詢樹型結(jié)構(gòu)

來源:本站原創(chuàng)|時間:2020-01-10|欄目:MsSql|點擊:

一、with as 公用表表達(dá)式

  類似VIEW,但是不并沒有創(chuàng)建對象,WITH AS 公用表表達(dá)式不創(chuàng)建對象,只能被后隨的SELECT語句,其作用:

  1. 實現(xiàn)遞歸查詢(樹形結(jié)構(gòu))

  2. 可以在一個語句中多次引用公用表表達(dá)式,使其更加簡潔

二、非遞歸的公共表達(dá)式

  可以是定義列或自動列和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 創(chuàng)建的表達(dá)式,它的連接條件就是遞歸的條件。可以從根節(jié)點往下查找,從子節(jié)點往父節(jié)點查找。只需要顛倒一下連接條件。例如代碼中條件改為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) 設(shè)置最大遞歸次數(shù)。例如上訴結(jié)果Level 最大值為2表示遞歸兩次。我們設(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)

好了這篇文章就介紹到這了,希望能幫助到你。

上一篇:sql server日志處理不當(dāng)造成的隱患詳解

欄    目:MsSql

下一篇:詳解將DataGrip連接到MS SQL Server的方法

本文標(biāo)題:SQL Server 通過with as方法查詢樹型結(jié)構(gòu)

本文地址:http://www.jygsgssxh.com/a1/MsSql/10277.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有