如何在不使用循环的情况下将拆分量插入表中?

时间:2012-04-02 01:54:02

标签: sql sql-server

我需要将一个金额拆分成多个部分并插入一个名为installment的表中,如何在不使用循环的情况下实现它?

declare @installment  as table (installment_index int identity(1,1),
                      amount money,
                      due_date datetime)

declare @total_amount money
declare @number_of_installment int
declare @amount money
declare @i int
declare @date datetime

 set @date = getdate()
 set @number_of_installment = 20
 set @total_amount  = 5001.00
 set @amount = @total_amount  / @number_of_installment
 set @i= 1

while @i <= @number_of_installment
begin
  insert into @installment
  (amount,due_date) values (@amount, dateadd(month,@i,@date))
  set @i = @i + 1
end

1 个答案:

答案 0 :(得分:5)

这将取代while循环:

;with numbers as (
   select 1 number
   union all
   select number + 1
   from numbers
   where number < @number_of_installment
)
insert into @installment (amount,due_date) 
select @amount, dateadd(month,number,@date)
from numbers
option (maxrecursion 0)

CTE编号返回从1到@number_of_installment的数字表 insert使用此表将@number_of_installment记录插入@installment。

编辑:

我必须提到的是,根据this article,为了类似的目的,没有什么比数字/日期的辅助表更好。