Hello every body, can anyone help me ?
I will describe my problem. First, i have 2 table name tbStock andtbSalesDetail. Column in tbStock and tbSalesDetail is like this :
CREATE TABLE tbStock ( idStock INT PRIMARY KEY, nameStock VARCHAR(250) NOT NULL, qtyStock FLOAT NOT NULL ); GO INSERT INTO tbStock (idStock, nameStock, qtyStock) VALUES (0, 'Apple', 100); INSERT INTO tbStock (idStock, nameStock, qtyStock) VALUES (1, 'Banana', 80); GO CREATE TABLE tbSalesDetail ( idData BIGINT IDENTITY(0,1) PRIMARY KEY, invoiceNumber VARCHAR(20) NOT NULL, idStock INT NOT NULL, qtySales FLOAT NOT NULL ); GO INSERT INTO tbSalesDetail (invoiceNumber,idStock,qtySales) VALUES ('JL001',0,10); INSERT INTO tbSalesDetail (invoiceNumber,idStock,qtySales) VALUES ('JL001',1,5); GO
Then, i want to update qtyStock in tbStock when data insert into tbSalesDetail or delete from tbSalesDetail with trigger. (In this case, i use delete from tbSalesDetail). So, i create trigger like this :
CREATE TRIGGER tbSalesDetail_Trigger_Delete ON tbSalesDetail FOR DELETE AS BEGIN DECLARE @idStockX INT, @qtySalesX FLOAT; SELECT @idStockX=idStock, @qtySalesX=qtySales FROM deleted; UPDATE tbStock SET qtyStock=qtyStock+@qtySalesX WHERE idStock=@idStockX; END GO
The trigger is run. I hope if i run delete command like :
DELETE FROM tbSalesDetail WHERE invoiceNumber='JL001';
will make the quantity of stock become like this :
Product Apple (idStock=0) = 100+10=110
Product Banana (idStock=1) = 80+5=85
But in the fact, Quantity Apple is True (110) and Quantity Banana isFalse (still 80).
I know this problem because trigger only run for first row. So how can i update each data in affected row with trigger ? (I use Windows 7 SP1 32 bit and SQL Server 2012 SP1 Express Edition)