Now between the recrods with Invoices 102 and 44, both have the same date, so what is the criteria to assign the @Field to Qty?Here's something to get you started. If you understand the logic you can take it from there:Declare @t Table(ProductId int,Invoice int, Date datetime, Qty int, Diff int)Insert into @t Select 1,97 ,'01/01/2006' ,3 ,0 union allSelect 1,102 ,'01/07/2007' ,2 ,0 union allSelect 1,44 ,'01/07/2007' ,7 ,0select * from @tDeclare @field int, @Qty int, @invoiceId intSet @field = 4While @field >0 Begin Select Top 1 @Qty = Qty, @invoiceId = Invoice from @t Where ProductId = 1 And Diff = 0Order by Date Asc IF @field >= @Qty Begin update @t Set Diff = @Qty Where productId = 1 And Invoice = @invoiceId Set @field = @field - @Qty End else Begin update @t Set Diff = @field Where productId = 1 And Invoice = @invoiceId Set @field = 0 End EndSelect * from @t
Dinakar Nethi************************Life is short. Enjoy it.************************http://weblogs.sqlteam.com/dinakar/