-- ============================================= -- Author: 余波(杭州) -- Create date: 2011/10/3 -- Description: 数字辅助表 -- ============================================= ---------创建1000000行的数字辅助表 ----sql server2000下的方法 if OBJECT_ID('nums') is not null drop table nums GO create table nums ( n int not null primary key ); declare @max as int,@rc as int; set @max=1000000; set @rc=1; insert into nums values(1); while @rc*2<=@max begin insert into nums select n+@rc from nums; set @rc=@rc*2; end insert into nums select n+@rc from nums where n<=@max ----cte实现(一) declare @num bigint set @num=1000000; with cte1 as ( select 1 as n union all select n+1 from cte1 where n<@num )select * from cte1 option (maxrecursion 0) ---这句很重要,不用这句会出现如下错误 /* 语句被终止。完成执行语句前已用完最大递归 100 */ ----cte实现(二) ;with cte_base as ( select 1 as n union all select n+1 from cte_base where n<CEILING(SQRT(1000000)) ), cte_expand as ( select 1 as n from cte_base a,cte_base b ) , cte_nums as ( select ROW_NUMBER() over(order by n) as n from cte_expand )select n from cte_nums where n<=1000000 option (maxrecursion 0) ---cte实现(三),三种方法中最好的一种,不需要控制maxrecursion ;with cte1 as ( select 1 as n ) , cte2 as ( select 1 as n from cte1 a,cte1 b ) , cte3 as ( select 1 as n from cte2 a,cte2 b ) , cte4 as ( select 1 as n from cte3 a,cte3 b ) , cte5 as ( select 1 as n from cte4 a,cte4 b ) , cte6 as ( select ROW_NUMBER() over (order by n) as number from cte5 ) select number from cte6 where number<=1000000