上周一直在看CTE因为里面都是一个表,或者说看的基本上都是可以拿来直接用SQL自己可以描述的,但是看到的代码的程序自己还是没有看太懂,只是能猜,有不确定性。
今天上午闲来测试了一下下:
use TESTDB
go
/*
----------------------------------
Server: Sql Server 2008
Create date: 2011/11/29
Author: CC
Descrioption: CTE测试
----------------------------------
*/
create table test_cte
(
aa int,
bb int,
cc int,
dd int
)
insert into test_cte
select 1,1,1,1
union all
select 1,1,1,2
union all
select 1,1,1,3
union all
select 1,1,1,4
create table test_cte1
(
aa int,
bb int,
ee int,
ff int
)
insert into test_cte1
select 1,2,3,2
union all
select 2,3,4,3
union all
select 3,4,5,4
union all
select 1,2,3,5
select * from test_cte;
select * from test_cte1;
go
自己开始的时候是这样写的:
with cte_test as
(
SELECT AA as bb,BB as bb, dd as cc FROM test_cte
union all
select test_cte1.aa as aa,test_cte1.bb as bb,test_cte1.ff as cc from test_cte1 join cte_test on cte_test.cc=test_cte1.ff
)
select * from cte_test ;
go
很明显这个是死循环,但是自己不知道,只是会有出错信息:消息 530,级别 16,状态 1,第 1 行
语句被终止。完成执行语句前已用完最大递归 100。
还以为是递归没有用过,百度看一下递归的最大数据是可以修改的,但是改了之后还是这样。
这就是说我想的有问题
思考了一下,改为了下面的语句:
with cte_test as
(
SELECT AA as bb,BB as bb, dd as cc FROM test_cte
union all
select 5+test_cte1.aa as aa,5+test_cte1.bb as bb,5+test_cte1.ff as cc
from test_cte1 join cte_test on cte_test.cc=test_cte1.ff
)
select * from cte_test;
go
结果是:
bb bb cc
----------- ----------- -----------
1 1 1
1 1 2
1 1 3
1 1 4
8 9 9
7 8 8
6 7 7
(7 行受影响)
这样就一目了然,就是第一SELECT其实就是CTE_TEST的结果,然后第二个查询再拿来使用,然后再来把最后的结果存入到CTE_TEST中。
--使用option(maxrecursion 1000可更新最大递归数)
--如:
select * from cte_test option(MAXRECURSION 1000);
go