<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>中文 &#187; sgear</title>
	<atom:link href="http://software.intel.com/zh-cn/blogs/author/sgear/feed/" rel="self" type="application/rss+xml" />
	<link>http://software.intel.com/zh-cn/blogs</link>
	<description></description>
	<lastBuildDate>Sat, 26 May 2012 06:34:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>SQL 中使用 WITH AS 提高性能 － 使用公用表表达式（CTE）简化嵌套 SQL</title>
		<link>http://software.intel.com/zh-cn/blogs/2011/03/24/sql-with-as-cte-sql/</link>
		<comments>http://software.intel.com/zh-cn/blogs/2011/03/24/sql-with-as-cte-sql/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 08:03:42 +0000</pubDate>
		<dc:creator>sgear</dc:creator>
				<category><![CDATA[其他]]></category>
		<category><![CDATA[博客征文专栏]]></category>

		<guid isPermaLink="false">http://software.intel.com/zh-cn/blogs/2011/03/24/sql-with-as-cte-sql/</guid>
		<description><![CDATA[  一．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短语里的数据放入一个全局临时表里。很多查询通过这种方法都可以提高速度。 二．使用方法 先看下面一个嵌套的查询语句： select * from person.StateProvince where CountryRegionCode in (select CountryRegionCode from person.CountryRegion where Name like 'C%') 上面的查询语句使用了一个子查询。虽然这条SQL语句并不复杂，但如果嵌套的层次过多，会使SQL语句非常难以阅读和维护。因此，也可以使用表变量的方式来解决这个问题，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 [...]]]></description>
			<content:encoded><![CDATA[<p> </p>
<p>一．WITH AS的含义<br />
WITH AS短语，也叫做子查询部分（subquery factoring），可以让你做很多事情，定义一个SQL片断，该SQL片断会被整个SQL语句所用到。有的时候，是为了让SQL语句的可读性更高些，也有可能是在UNION ALL的不同部分，作为提供数据的部分。<br />
特别对于UNION ALL比较有用。因为UNION ALL的每个部分可能相同，但是如果每个部分都去执行一遍的话，则成本太高，所以可以使用WITH AS短语，则只要执行一遍即可。如果WITH AS短语所定义的表名被调用两次以上，则优化器会自动将WITH AS短语所获取的数据放入一个TEMP表里，如果只是被调用一次，则不会。而提示materialize则是强制将WITH AS短语里的数据放入一个全局临时表里。很多查询通过这种方法都可以提高速度。</p>
<p>二．使用方法<br />
先看下面一个嵌套的查询语句：</p>
<p>select * from person.StateProvince where CountryRegionCode in<br />
(select CountryRegionCode from person.CountryRegion where Name like 'C%')</p>
<p>上面的查询语句使用了一个子查询。虽然这条SQL语句并不复杂，但如果嵌套的层次过多，会使SQL语句非常难以阅读和维护。因此，也可以使用表变量的方式来解决这个问题，SQL语句如下：</p>
<p>declare @t table(CountryRegionCode nvarchar(3))<br />
insert into @t(CountryRegionCode) (select CountryRegionCode from person.CountryRegion where Name like 'C%')</p>
<p>select * from person.StateProvince where CountryRegionCode<br />
in (select * from @t)</p>
<p>虽然上面的SQL语句要比第一种方式更复杂，但却将子查询放在了表变量@t中，这样做将使SQL语句更容易维护，但又会带来另一个问题，就是性能的损失。由于表变量实际上使用了临时表，从而增加了额外的I/O开销，因此，表变量的方式并不太适合数据量大且频繁查询的情况。为此，在SQL Server 2005中提供了另外一种解决方案，这就是公用表表达式（CTE），使用CTE，可以使SQL语句的可维护性，同时，CTE要比表变量的效率高得多。</p>
<p>下面是CTE的语法：</p>
<p>[ WITH [ ,n ] ]<br />
::=<br />
expression_name [ ( column_name [ ,n ] ) ]<br />
AS<br />
( CTE_query_definition )</p>
<p>现在使用CTE来解决上面的问题，SQL语句如下：</p>
<p>with<br />
cr as<br />
(<br />
select CountryRegionCode from person.CountryRegion where Name like 'C%'<br />
)</p>
<p>select * from person.StateProvince where CountryRegionCode in (select * from cr)</p>
<p>其中cr是一个公用表表达式，该表达式在使用上与表变量类似，只是SQL Server 2005在处理公用表表达式的方式上有所不同。</p>
<p>在使用CTE时应注意如下几点：<br />
1. CTE后面必须直接跟使用CTE的SQL语句（如select、insert、update等），否则，CTE将失效。如下面的SQL语句将无法正常使用CTE：</p>
<p>with<br />
cr as<br />
(<br />
select CountryRegionCode from person.CountryRegion where Name like 'C%'<br />
)<br />
select * from person.CountryRegion -- 应将这条SQL语句去掉<br />
-- 使用CTE的SQL语句应紧跟在相关的CTE后面 --<br />
select * from person.StateProvince where CountryRegionCode in (select * from cr)</p>
<p>2. CTE后面也可以跟其他的CTE，但只能使用一个with，多个CTE中间用逗号（,）分隔，如下面的SQL语句所示：<br />
with<br />
cte1 as<br />
(<br />
select * from table1 where name like 'abc%'<br />
),<br />
cte2 as<br />
(<br />
select * from table2 where id &gt; 20<br />
),<br />
cte3 as<br />
(<br />
select * from table3 where price &lt; 100<br />
)<br />
select a.* from cte1 a, cte2 b, cte3 c where a.id = b.id and a.id = c.id</p>
<p>3. 如果CTE的表达式名称与某个数据表或视图重名，则紧跟在该CTE后面的SQL语句使用的仍然是CTE，当然，后面的SQL语句使用的就是数据表或视图了，如下面的SQL语句所示：</p>
<p>-- table1是一个实际存在的表<br />
with<br />
table1 as<br />
(<br />
select * from persons where age &lt; 30<br />
)<br />
select * from table1 -- 使用了名为table1的公共表表达式<br />
select * from table1 -- 使用了名为table1的数据表</p>
<p>4. CTE 可以引用自身，也可以引用在同一 WITH 子句中预先定义的 CTE。不允许前向引用。</p>
<p>5. 不能在 CTE_query_definition 中使用以下子句：</p>
<p>（1）COMPUTE 或 COMPUTE BY</p>
<p>（2）ORDER BY（除非指定了 TOP 子句）</p>
<p>（3）INTO</p>
<p>（4）带有查询提示的 OPTION 子句</p>
<p>（5）FOR XML</p>
<p>（6）FOR BROWSE</p>
<p>6. 如果将 CTE 用在属于批处理的一部分的语句中，那么在它之前的语句必须以分号结尾，如下面的SQL所示：</p>
<p>declare @s nvarchar(3)<br />
set @s = 'C%'<br />
; -- 必须加分号<br />
with<br />
t_tree as<br />
(<br />
select CountryRegionCode from person.CountryRegion where Name like @s<br />
)<br />
select * from person.StateProvince where CountryRegionCode in (select * from t_tree)</p>
<p>CTE除了可以简化嵌套SQL语句外，还可以进行递归调用，关于这一部分的内容将在下一篇文章中介绍。</p>
]]></content:encoded>
			<wfw:commentRss>http://software.intel.com/zh-cn/blogs/2011/03/24/sql-with-as-cte-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

