SQL循环和增量

问题描述

| 我正在使用sql Server 2008 我有以下sql获取从今天到2012年12月31日之间的所有日期。我现在要做的是从10000开始,并相等地递增此值,因此在12月31日,我的值为150000。
Declare @projection table(d datetime,t decimal)
Declare @d datetime
Declare @t decimal(18,2)

set @d=\'20110527\'
set @t=100000

While @d<=\'20121231\'
Begin
Insert into @projection values (@d,@t)
set @d=@d+1
End
Select d as DateCol,t as TotalRevenue from @projection
任何帮助,不胜感激     

解决方法

        这从10000到150000线性内插
t
Declare @projection table(d datetime,t decimal)
Declare @d datetime,@d1 datetime,@d2 datetime
Declare @t decimal(18,4),@t1 decimal(18,@t2 decimal(18,@tincr decimal(18,4)

set @d1=\'20110527\'
set @d2=\'20121231\'
set @t1=10000
set @t2=150000

Set @tincr = (@t2-@t1)/DATEDIFF(D,@d1,@d2)

Set @d = @d1
set @t = @t1

While @d<=@d2
Begin
Insert into @projection values (@d,@t)
set @d=@d+1
Set @t=@t+@tincr
End
Select d as DateCol,t as TotalRevenue from @projection
请注意,我将小数精度提高到4,以使舍入误差不明显。