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
短语里的数据放入一个全局临时表里。很多查询通过这种方法都可以提高速度
样例:
with
cr as

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

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

注意:
1. CTE后面必须直接跟使用CTE的SQL语句(如select、insert、update等),否则,CTE将失效。
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)

2. CTE后面也可以跟其他的CTE,但只能使用一个with,多个CTE中间用逗号(,)分隔,如下面的SQL语
with
cte1 as

    select * from table1 where name like 'abc%'
), 
cte2 as

    select * from table2 where id > <strong>20</strong> 
), 
cte3 as

    select * from table3 where price < <strong>100</strong> 

select a.* from cte1 a, cte2 b, cte3 c where a.id = b.id and a.id = c.id
3. 如果CTE的表达式名称与某个数据表或视图重名,则紧跟在该CTE后面的SQL语句使用的仍然是CTEwith
table1 as

    select * from persons where age < <strong>30</strong> 

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

4.CTE 可以引用自身,也可以引用在同一WITH 子句中预先定义的CTE。不允许前向引用
5. 不能在CTE_query_definition 中使用以下子句:

(1)COMPUTE 或COMPUTE BY

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

(3)INTO

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

(5)FOR XML

(6)FOR BROWSE
6. 如果将CTE 用在属于批处理的一部分的语句中,那么在它之前的语句必须以分号结尾,如下面的SQLdeclare @s nvarchar(<strong>3</strong>) 
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)

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐