公用表表达式(CTE) with as 片段
1.为什么用CTE,而不用表变量,
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语句要比第一种方式更复杂,但却将子查询放在了表变量@t中,这样做将使SQL语句更容易维护,但又会带来另一个问题,就是性能的损失。由于表变量实际上使用了临时表,从而增加了额外的I/O开销,因此,表变量的方式并不太适合数据量大且频繁查询的情况。为此,在SQL Server 2005中提供了另外一种解决方案,这就是公用表表达式(CTE),使用CTE,可以使SQL语句的可维护性,同时,CTE要比表变量的效率高得多。
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:
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。不允许前向引用。
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)
CTE除了可以简化嵌套SQL语句外,还可以进行递归调用,关于这一部分的内容将在下一篇文章中介绍。
最新文章
- observejs改善组件编程体验
- 服务器判断http是否中断
- Go语言工程结构
- javascript中event.keycode大全
- 完美让IE兼容input placeholder属性的jquery实现
- javascript 控制input
- 解析JSON对象与字符串之间的相互转换
- 深入理解 JavaScript 异步系列(1)—— 什么是异步
- VUE2.0增删改查附编辑添加model(弹框)组件共用
- 【转载】Perl中的引用
- Maven替换为国内仓库
- vue_class 绑定_style 绑定
- vue基础篇---路由的实现
- easyui---tree异步加载
- 经典面试题sql基础篇-50常用的sql语句(有部分错误)
- AtCoder Tenka1 Programmer Beginner Contest 解题报告
- debian修改ssh端口
- go语言实战教程:Redis实战项目应用
- 相对定位position: relative;
- ext笔记
热门文章
- TCP网络调试助手上提示错误:“1035 未知错误”的有效解决方法,本人实测确实可行
- docker+hexo 搭建博客
- JS 上传图片压缩,原比例压缩
- Fleck WebSocket使用
- Suffix Tree(后缀树)
- 【K-means算法】matlab代码实例学习
- Newtonsoft.Json 版本不一致导致错误
- Android的界面组件使用之ImageButton和ImageView,ImageSwitcher和GridView
- 阿里云Centos7安装mysql5.7
- 吴裕雄--天生自然PythonDjangoWeb企业开发:框架基础和技术选型