I need to loop through all the warehouses in a given PLANT (by the given "PlantId") and total the transaction data into a summary "InventoryMovement" table: I need to totalize, for each inventory item, the initial inventories, the purchases, sales, etc....
Using the "initial inventory" as an example. For each warehouse, I need to INSERT into the "InventoryMovement" the initial inventory if the record doesn't exist, but UPDATE it if there already is a record for the given item.
I'm in a mental block and can't figure out how to do this...
Parameters: @PlantId - Plant we are working on
@InitialDate - Initial date
FOR WarehousesLOOP AS CURSOR_Warehouses
CURSOR FOR
SELECT WarehouseId AS @WarehouseId
FROM PlantWarehouses
WHERE PlantId = @PlantId
DO
-------------------------------------------------------------------------------------------------
-- INITIAL INVENTORY
-------------------------------------------------------------------------------------------------
INSERT INTO InventoryMovement
ON EXISTING UPDATE
(PlantId,ItemId,MovementDate,InitialInventoryQty)
SELECT @PlantId,ItemId,InventoryDate,Quantity
FROM InventoryCount WHERE WarehouseId = @WarehouseId AND InventoryDate = @InitialDate
--
END IF;
END FOR;
The above fails because for rows that already exists I don't want to just overwrite them, I need to ADD the existing's row InitialInventoryQty with the new warehouse's qty.
Does this make sense? How do I do this sort of thing in SQL?
Best regards,
Edgard