构建数字辅助表

-- =============================================                  
-- 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


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值