SQL.WITH AS.公用表表达式(CTE)

一.WITH AS的含义 WITH AS短语,也叫作子查询部分(subquery factoring),可让你作不少事情,定义一个SQL片段,该SQL片段会被整个SQL语句所用到。有的时候,是为了让SQL语句的可读性更高些,也有多是在UNION ALL的不一样部分,做为提供数据的部分。 特别对于UNION ALL比较有用。由于UNION ALL的每一个部分可能相同,可是若是每一个部分都去执行一遍的话,则成本过高,因此可使用WITH AS短语,则只要执行一遍便可。若是WITH AS短语所定义的表名被调用两次以上,则优化器会自动将WITH AS短语所获取的数据放入一个TEMP表里,若是只是被调用一次,则不会。而提示materialize则是强制将WITH AS短语里的数据放入一个全局临时表里。不少查询经过这种方法均可以提升速度。express

二.使用方法 先看下面一个嵌套的查询语句:性能

1优化

2code

select * from person.StateProvince where CountryRegionCode in递归

(select CountryRegionCode from person.CountryRegion where Name like 'C%') 


上面的查询语句使用了一个子查询。虽然这条SQL语句并不复杂,但若是嵌套的层次过多,会使SQL语句很是难以阅读和维护。所以,也可使用表变量的方式来解决这个问题,SQL语句以下:

1ip

2get

3it

4io

declare @t table(CountryRegionCode nvarchar(3))table

insert into @t(CountryRegionCode) (select CountryRegionCode from person.CountryRegion where Name like 'C%')

select * from person.StateProvince where CountryRegionCode in (select * from @t)

虽然上面的SQL语句要比第一种方式更复杂,但却将子查询放在了表变量@t中,这样作将使SQL语句更容易维护,但又会带来另外一个问题,就是性能的损失。因为表变量实际上使用了临时表,从而增长了额外的I/O开销,所以,表变量的方式并不太适合数据量大且频繁查询的状况。为此,在SQL Server 2005中提供了另一种解决方案,这就是公用表表达式(CTE),使用CTE,可使SQL语句的可维护性,同时,CTE要比表变量的效率高得多。 

下面是CTE的语法:

1

2

3

4

5

[ WITH <common_table_expression> [ ,n ] ]

<common_table_expression>::=

expression_name [ ( column_name [ ,n ] ) ]

AS

    ( CTE_query_definition ) 


如今使用CTE来解决上面的问题,SQL语句以下:

1

2

3

4

5

6

7

with

cr as

(

select CountryRegionCode from person.CountryRegion where Name like 'C%'

)

select * from person.StateProvince where CountryRegionCode in (select * from cr)

其中cr是一个公用表表达式,该表达式在使用上与表变量相似,只是SQL Server 2005在处理公用表表达式的方式上有所不一样。

在使用CTE时应注意以下几点:

  1. CTE后面必须直接跟使用CTE的SQL语句(如select、insert、update等),不然,CTE将失效。以下面的SQL语句将没法正常使用CTE:

1

2

3

4

5

6

7

8

with

cr as

(

select CountryRegionCode from person.CountryRegion where Name like 'C%'

)

select * from person.CountryRegion -- 应将这条SQL语句去掉

-- 使用CTE的SQL语句应紧跟在相关的CTE后面 --

select * from person.StateProvince where CountryRegionCode in (select * from cr)

  1. CTE后面也能够跟其余的CTE,但只能使用一个with,多个CTE中间用逗号(,)分隔,以下面的SQL语句所示:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

  1. 若是CTE的表达式名称与某个数据表或视图重名,则紧跟在该CTE后面的SQL语句使用的仍然是CTE,固然,后面的SQL语句使用的就是数据表或视图了,以下面的SQL语句所示:

-- table1是一个实际存在的表

1

2

3

4

5

6

7

with

table1 as

(

select * from persons where age < 30

)

select * from table1 -- 使用了名为table1的公共表表达式

select * from table1 -- 使用了名为table1的数据表

  1. CTE 能够引用自身,也能够引用在同一 WITH 子句中预先定义的 CTE。不容许前向引用。

  2. 不能在 CTE_query_definition 中使用如下子句:

(1)COMPUTE 或 COMPUTE BY

(2)ORDER BY(除非指定了 TOP 子句)

(3)INTO

(4)带有查询提示的 OPTION 子句

(5)FOR XML

(6)FOR BROWSE

  1. 若是将 CTE 用在属于批处理的一部分的语句中,那么在它以前的语句必须以分号结尾,以下面的SQL所示:

1

2

3

4

5

6

7

8

9

declare @s nvarchar(3)

set @s = 'C%'

; -- 必须加分号

with

t_tree as

(

select CountryRegionCode from person.CountryRegion where Name like @s

)

select * from person.StateProvince where CountryRegionCode in (select * from t_tree)

CTE除了能够简化嵌套SQL语句外,还能够进行递归调用。

实例展现

用户表

1

2

3

SELECT CONVERT(varchar(100), [RegistDate], 23) dates,COUNT(*) addsuers

FROM [FenxCloudZj].[dbo].[tourol_B2CUser] where [RegistDate]>DATEADD(M,-1,getdate())

group by CONVERT(varchar(100), [RegistDate], 23)

image

接下来使用CTE拼接起来

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/****** Script for SelectTopNRows command from SSMS ******/

WITH CET AS(

SELECT CONVERT(varchar(100), [RegistDate], 23) dates,COUNT(*) addusers

FROM [FenxCloudZj].[dbo].[tourol_B2CUser] where [RegistDate]>DATEADD(M,-1,getdate())

group by CONVERT(varchar(100), [RegistDate], 23)

)

SELECT CONVERT(varchar(22),TABLE4.DATES, 102 ) dates,ISNULL(TABLE5.adduers,0) adduers FROM

(

select DATEADD(D,table2.number,table1.mindates) dates

from (select MIN(dates) mindates,MAX(dates) maxdates from CET) table1,

master..spt_values table2

where table2.type='p' and DATEADD(D,table2.number,table1.mindates)<=table1.maxdates

)TABLE4

LEFT JOIN CET TABLE5 ON TABLE4.DATES=TABLE5.DATES

image

相关文章
相关标签/搜索