使用公用表表达式(CTE)简化嵌套SQL 和进行递归调用
1.使用CTE简化嵌套sql
先看下面一个嵌套的查询语句:
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 * from @t)
虽然上面的SQL语句要比第一种方式更复杂,但却将子查询放在了表变量@t中,这样做将使SQL语句更容易维护,但又会带来另一个问题,就是性能的损失。由于表变量实际上使用了临时表,从而增加了额外的I/O开销,因此,表变量的方式并不太适合数据量大且频繁查询的情况。为此,在SQL Server 2005中提供了另外一种解决方案,这就是公用表表达式(CTE),使用CTE,可以使SQL语句的可维护性,同时,CTE要比表变量的效率高得多。
下面是CTE的语法:
[ WITH <common_table_expression> [ ,n ] ]
<common_table_expression>::=
expression_name [ ( column_name [ ,n ] ) ]
AS
( CTE_query_definition )
现在使用CTE来解决上面的问题,SQL语句如下:
with
cr as
(
select CountryRegionCode from person.CountryRegion where 
相关文档:
string error_syntaxfromSQL, error_create
string new_sql, new_syntax
new_sql = 'SELECT emp_data.emp_id, ' &
& ......
1:
Sql server 2005日志文件太大,使其减小的方法
运行下面的三行 PMDataCenter 为数据库名:
backup log PMDataCenter with NO_LOG
backup log PMDataCenter with TRUNCATE_ONLY
DBCC SHRINKDATABASE(PMDataCenter) ......
SQL Server 2005 (MSSQLSERVER) 服务不能启动
原因:VIA协议”给启用了,停用“VIA协议”问题解决。
"VIA协议"停用方法:开始->程序->Microsoft SQL Server 2005->配置工具->SQL Server Configuration Manager ->打开后找到"SQL Server 2005 网络配置"->MSSQLSERVER 属性的协议 &nb ......
--查询应用程序的等待
SELECT TOP 10
wait_type,waiting_tasks_count AS tasks,
wait_time_ms,max_wait_time_ms AS max_wait,
signal_wait_time_ms AS signal
from sys.dm_os_wait_stats
ORDER BY wait_time_ms DESC
--查询在任一时刻所有授权给当前执行事务或当前执行事务等待的锁
SELECT
request_session_id A ......
declare @CausName as char(20) declare @causenameid as int declare
@Description as varchar(200) declare @Caus_Id as int
declare @sign as char(20)
create table #tb ( Caus_Id int,CausName varchar(20),causNameid int,Caus_Description varchar(200),标志 varchar(20))
DECLARE myCursor1 CURSOR F ......