您好,欢迎访问一九零五行业门户网

【数据库】数据库中with...as...的用法

一.with as的含义 with as短语,也叫做子查询部分(subquery factoring),对于union all比较有用。因为union all的每个部分可能相同,但是如果每个部分都去执行一遍的话,则成本太高,所以可以使用with as短语,则只要执行一遍即可。如果with as短语所定义
一.with as的含义with as短语,也叫做子查询部分(subquery factoring),对于union all比较有用。因为union all的每个部分可能相同,但是如果每个部分都去执行一遍的话,则成本太高,所以可以使用with as短语,则只要执行一遍即可。如果with as短语所定义的表名被调用两次以上,则优化器会自动将with as短语所获取的数据放入一个temp表里,如果只是被调用一次,则不会。而提示materialize则是强制将with as短语里的数据放入一个全局临时表里。
二.语法
[ with [ ,n ] ]::= expression_name [ ( column_name [ ,n ] ) ] as( cte_query_definition )
现在使用cte来解决上面的问题,sql语句如下:
with cr as( select countryregioncode from person.countryregion where name like 'c%')select * from person.stateprovince where countryregioncode in (select * from cr)
在使用cte时应注意如下几点:
1. 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
-- 应将这条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 > 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
3. 如果cte的表达式名称与某个数据表或视图重名,则紧跟在该cte后面的sql语句使用的仍然是cte,当然,后面的sql语句使用的就是数据表或视图了,如下面的sql语句所示:-- table1是一个实际存在的表with table1 as( select * from persons where age < 30)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 用在属于批处理的一部分的语句中,那么在它之前的语句必须以分号结尾,如下面的sql所示:
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)
其它类似信息

推荐信息