I have two table Stocks and Purchases
CREATE TABLE Stocks
(
id int PRIMARY KEY IDENTITY(1,1),
itemId int NOT NULL,
qty int NOT NULL,
status NVarChar(50) NOT NULL,
)
CREATE TABLE Purchases
(
id int PRIMARY KEY IDENTITY(1,1),
itemId int NOT NULL,
suppId int NOT NULL,
qty int NOT NULL,
Date NVarChar(50) NOT NULL,
status NVarChar(50) NOT NULL,
)
Here is what I want do:
ON Inserting Multiple Records into Purchases table, I want Create a Trigger that Iterates over each Record Inserted and Check itemId FROM the Stocks Table
UPDATE TheQuantity(qty in this case) of each itemId found AND INSERT into the Stocks Table if itemId isn't found
I have tried several ways, in fact I have been struggling with it since yesterday.
this Post was the closest one I have seen but could figure out what is going on, seems like it's only Updating already existing records
Here is what I have tried so far, I meanthe closest I came
CREATE trigger [dbo].[trPurchaseInsert] on [dbo].[Purchases] FOR
INSERT
AS
DECLARE @id int;
DECLARE @itemId int;
DECLARE @status NVarChar(50) = 'available';
SELECT @itemId=i.ItemId FROM INSERTED i
IF EXISTS(SELECT * FROM Stocks WHERE itemId=@itemId)
BEGIN
SET NOCOUNT ON;
DECLARE @itemIdUpdate int;
DECLARE @qty int;
SELECT @qty=[quantity], @itemIdUpdate=[itemId] FROM INSERTED i
UPDATE Stocks SET qty=qty+@qty WHERE itemId=@itemIdUpdate
END
ELSE
BEGIN
SET NOCOUNT ON;
INSERT INTO Stocks SELECT [itemId], [id], [quantity], @status
FROM INSERTED i
END
this works fine in a single Insert but doesn't work when multiple records are inserted into the Purchase Table at once
The above Trigger Updates the first itemId only and doesn't update the rest or even insert new ones if one itemid is found
The Goal here is to Update in stock items if itemid is found and Insert if itemId isn't found
For Further Details see this SQL Fiddle. It contains Tables & what I have tried with commented details
I have seen several comments advising to use set base operations with joins but couldn't figure a direction
How can I get it to work?