declare @BillId BIGINT DECLARE @GoodsId BIGINT DECLARE @CompId BIGINT DECLARE @BillTime DATETIME DECLARE @BookInventory DECIMAL(18,6) DECLARE @PhyInventory DECIMAL(18,6) DECLARE @DiffQuantity DECIMAL(18,6) DECLARE @Quantity DECIMAL(18,6) DECLARE @DetailId BIGINT DECLARE @Count INT SELECT @Count = 0 declare #Bills cursor for SELECT T.FCompId,T.FBillId,T.FBillTime FROM TTakeStockBill AS T WHERE 1=1 -- AND T.FCompId = 5248908718224980451 AND T.FState = 1 ORDER BY FBillTime open #Bills fetch #Bills into @CompId,@BillId,@BillTime while @@fetch_status=0 begin print @BillTime print @billId declare #Details cursor for SELECT D.FGoodsId, B.FBookInventory,B.FPhyInventory,B.FId FROM TTakeStockDetail AS D,TTakeStockDetailBatch AS B WHERE D.FId = B.FDetailId AND D.FBillId = @BillId ORDER BY D.FSequence open #Details fetch #Details into @GoodsId,@BookInventory,@PhyInventory,@DetailId while @@fetch_status=0 begin select @Quantity = SUM(FInStdQuantity) - SUM(FOutStdQuantity) FROM TInventoryHist AS A WHERE A.FCompId = @CompId AND A.FGoodsId = @GoodsId AND A.FTime < @BillTime SELECT @Quantity = ISNULL(@Quantity,0) IF @Quantity != @BookInventory BEGIN select @Count = @Count + 1 --错误的 print '产品Id' + CAST( @GoodsId AS VARCHAR(20)) + ',真实账面库存:' + CAST( @Quantity AS VARCHAR(20)) + ',单据账面库存:' + CAST( @BookInventory AS VARCHAR(20)) + ',实际库存:' + CAST( @PhyInventory AS VARCHAR(20)) + ',单据差异:' + CAST( @BookInventory - @PhyInventory AS VARCHAR(20)) + ',实际差异:' + CAST( @Quantity - @PhyInventory AS VARCHAR(20)) UPDATE TTakeStockDetailBatch SET FBookInventory = @Quantity WHERE FId = @DetailId END fetch #Details into @GoodsId,@BookInventory,@PhyInventory,@DetailId end close #Details deallocate #Details if @Count > 0 break fetch #Bills into @CompId,@BillId,@BillTime end close #Bills deallocate #Bills return SELECT * FROM TCompany