国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > SQL Server > 正文

SQL Server 通過with as方法查詢樹型結構

2020-07-25 12:35:39
字體:
來源:轉載
供稿:網友

一、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)

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宽城| 峨眉山市| 吴忠市| 佛山市| 五莲县| 留坝县| 奇台县| 临夏县| 黔西县| 武定县| 鄂尔多斯市| 屯留县| 贵阳市| 拉孜县| 太仆寺旗| 大姚县| 浦北县| 平湖市| 塘沽区| 额敏县| 吴川市| 香港 | 毕节市| 美姑县| 丰都县| 津南区| 平邑县| 绿春县| 巴马| 平顶山市| 彭山县| 丰城市| 浦东新区| 甘泉县| 易门县| 绵阳市| 吉水县| 台安县| 雅江县| 邵武市| 正安县|