with as短語,也叫做子查詢部分(subquery factoring),可以讓你做很多事情,定義乙個sql片斷,該sql片斷會被整個sql語句所用到。有的時候,是為了讓sql語句的可讀性更高些,也有可能是在union all的不同部分,作為提供資料的部分。
特別對於union all比較有用。因為union all的每個部分可能相同,但是如果每個部分都去執行一遍的話,則成本太高,所以可以使用with as短語,則只要執行一遍即可。
with as 查詢的模板
with test as(select
*from
表 union
allselect t.*
from 表 t,test m where t.id=
m.parentid )
select
distinct
*from test order
by id
自上到下
with test as(select cb_projectaccount.*
from
cb_projectaccount
union
allselect t.*
from cb_projectaccount t,test m where t.parentprojectaccountguid=
m.projectaccountguid )
select
distinct
*from test order
by projectaccountguid
自下到上遞迴
;with test as(select cb_projectaccount.*
from
cb_projectaccount
union
allselect t.*
from cb_projectaccount t,test m where m.projectaccountguid=
t.parentprojectaccountguid )
select
distinct
*from test order
by projectaccountguid desc
SQLServer 遞迴查詢
感謝文章遞迴查詢,正好趁此機會梳理一下資料庫的遞迴查詢 公用表表示式 cte 可以認為是在單個 select insert update delete 或 create view 語句的執行範圍內定義的臨時結果集。公用表表示式可以包括對自身的引用,這種表示式稱為遞迴公用表表示式。with expre...
sqlserver 遞迴查詢
有如下資料表 假如我們要查詢id為003的資料的所有子節點我們可以使用cte 遞迴查詢完成.sql view plain copy print?if object id tb n is notnull drop table tb create table tb id varchar 3 pid va...
sql server遞迴查詢
1 既然要談到sql,資料庫表是必須的 2 資料結構 3 獲取某個節點的所有子節點 傳統的寫法 sql2000 很麻煩,暫且就不寫了 來看看cte的寫法 create proc sp gettreebyid treeid int asbegin with ctetree as select from...