一、WITH AS 的含義
WITH AS 短語, 也叫做子查詢部分(subqery factoring)库糠,可以定義一個(gè)SQL片段,改片段回被整個(gè)SQL語句用到涮毫∷才罚可以使SQL語句的可讀性更高贷屎,也可以再UNION ALL的不同部分,作為提供數(shù)據(jù)部分艘虎。
二.使用方法
先看下面一個(gè)嵌套的查詢語句:
select * from person.StateProvince where CountryRegionCode in
(select CountryRegionCode from person.CountryRegion where Name like 'C%')
上面的查詢語句使用了一個(gè)子查詢豫尽。雖然這條SQL語句并不復(fù)雜,但如果嵌套的層次過多顷帖,會(huì)使SQL語句非常難以閱讀和維護(hù)。因此渤滞,也可以使用表變量的方式來解決這個(gè)問題贬墩,SQL語句如下:
declare @t table(CountryRegionCode nvarchar(3))
insert into @t(CountryRegionCode) (select CountryRegionCode from person.CountryRegion where Name like 'C%')
select * from person.StateProvince where CountryRegionCode in (select * from @t)
雖然上面的SQL語句要比第一種方式更復(fù)雜,但卻將子查詢放在了表變量@t中妄呕,這樣做將使SQL語句更容易維護(hù)陶舞,但又會(huì)帶來另一個(gè)問題,就是性能的損失绪励。由于表變量實(shí)際上使用了臨時(shí)表肿孵,從而增加了額外的I/O開銷,因此疏魏,表變量的方式并不太適合數(shù)據(jù)量大且頻繁查詢的情況停做。為此,在SQL Server 2005中提供了另外一種解決方案大莫,這就是公用表表達(dá)式(CTE)蛉腌,使用CTE,可以使SQL語句的可維護(hù)性只厘,同時(shí)烙丛,CTE要比表變量的效率高得多。
三羔味、下面是CTE的語法:
[ WITH <common_table_expression> [ ,n ] ]
<common_table_expression>::=
expression_name [ ( column_name [ ,n ] ) ]
AS
( CTE_query_definition )
現(xiàn)在使用CTE來解決上面的問題河咽,SQL語句如下: *************重點(diǎn)
with
cr as
(
select CountryRegionCode from person.CountryRegion where Name like 'C%'
)
select * from person.StateProvince where CountryRegionCode in (select * from cr)
其中cr是一個(gè)公用表表達(dá)式,該表達(dá)式在使用上與表變量類似赋元,只是SQL Server 2005在處理公用表表達(dá)式的方式上有所不同忘蟹。
在使用CTE時(shí)應(yīng)注意如下幾點(diǎn):
- CTE后面必須直接跟使用CTE的SQL語句(如select、insert们陆、update等)寒瓦,否則,CTE將失效坪仇。如下面的SQL語句將無法正常使用CTE:
with
cr as
(
select CountryRegionCode from person.CountryRegion where Name like 'C%'
)
select * from person.CountryRegion -- 應(yīng)將這條SQL語句去掉
-- 使用CTE的SQL語句應(yīng)緊跟在相關(guān)的CTE后面 --
select * from person.StateProvince where CountryRegionCode in (select * from cr)
- CTE后面也可以跟其他的CTE杂腰,但只能使用一個(gè)with,多個(gè)CTE中間用逗號(,)分隔椅文,如下面的SQL語句所示:
with
cte1 as
(
select * from table1 where name like 'abc%'
),
cte2 as
(
select * from table2 where id > 20
),
cte3 as
(
select * from table3 where price < 100
)
select a.* from cte1 a, cte2 b, cte3 c where a.id = b.id and a.id = c.id
- 如果CTE的表達(dá)式名稱與某個(gè)數(shù)據(jù)表或視圖重名喂很,則緊跟在該CTE后面的SQL語句使用的仍然是CTE惜颇,當(dāng)然,后面的SQL語句使用的就是數(shù)據(jù)表或視圖了少辣,如下面的SQL語句所示:
-- table1是一個(gè)實(shí)際存在的表
with
table1 as
(
select * from persons where age < 30
)
select * from table1 -- 使用了名為table1的公共表表達(dá)式
select * from table1 -- 使用了名為table1的數(shù)據(jù)表