CSDN網友發佈了一個題目,如下連接所示:
http://topic.csdn.net/u/20090610/20/92c3d2eb-4ee5-4df1-bc09-2fd32254fa06_3.html
個人比較感興趣,於是試着給瞭如下答案:
首先創建表:
CREATE TABLE [dbo].[ProductOrder](
[pno] [int] NULL,
[pQty] [int] NULL,
[DayQty] [int] NULL,
[ProdOrder] [int] NULL
) ON [PRIMARY]
插入如下值:
1 100 40 1
2 30 20 2
3 20 10 3
創建下表保存結果:
create table DailyProd
(
[day] int,
pno int,
AQty int
)
下面是過程
truncate table DailyProd
select * into ProductOrder_tmp from ProductOrder --臨時表存放當前未生產完的產品
declare @day int
set @day=1 --天數計時器
while(exists(select * from ProductOrder_tmp)) --知道所有的產品被生產完
begin
declare prodCur cursor for select * from ProductOrder_tmp order by prodOrder asc
open prodCur
declare @pno int,@pqty int,@Dayqty int,@PO int,@sum float
fetch next from prodCur into @pno,@pQty,@DayQty,@PO
set @sum=1.0 --每個
while(@@fetch_status=0)
begin
if(@pQty>@DayQty*@sum)--該類產品今天沒有能力生產完
begin
update ProductOrder_tmp set pqty=pqty-dayqty*@sum where pno=@pno
insert into DailyProd values(@day,@pno,@DayQty*@sum)
set @sum=0
end
else --今天之後沒有餘量了
begin
delete from ProductOrder_tmp where pno=@pno
insert into DailyProd values(@day,@pno,@pQty)
set @sum=@sum-(cast(@pQty as float)/@DayQty)
end
fetch next from prodCur into @pno,@pQty,@DayQty,@PO
end
--清場
close prodCur
deallocate prodCur
set @day=@day+1
end
select * from DailyProd --顯示結果
drop table ProductOrder_tmp