In most cases the ideal is not to store calculation attributes in the tables, but if you want to make a TRIGGER
for this, would be as follows:
IF OBJECT_ID('tgr_itemvenda_ai', 'TR') IS NULL
BEGIN
EXEC('CREATE TRIGGER tgr_itemvenda_ai ON ItemVenda FOR INSERT AS BEGIN SELECT 1 END');
END;
GO
ALTER TRIGGER tgr_itemvenda_ai
ON ItemContrato
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
UPDATE p
SET p.Quantidade = p.Quantidade - i.Quantidade
FROM Produto p
INNER JOIN inserted i ON i.codProduto = p.codProduto;
END;
GO
The suggestion I give you not to need to use TRIGGER
is to use a stock table where you perform the closing monthly or as your need:
CREATE TABLE Estoque(
codEstoque INT PRIMARY KEY IDENTITY(1, 1),
codProduto INT NOT NULL,
Quantidade INT NOT NULL,
Inicio DATE NOT NULL,
Fim DATE NOT NULL,
CONSTRAINT fk_EstoqueProduto FOREIGN KEY(codProduto) REFERENCES Produto
ON DELETE CASCADE
ON UPDATE CASCADE
);
Whereas you have a column data
on the table Venda
:
SELECT e.codProduto,
CONVERT(VARCHAR(10), e.Inicio, 103) AS Inicio,
CONVERT(VARCHAR(10), e.Fim, 103) AS Fim,
e.Quantidade - SUM(iv.Quantidade) AS disponivelFim
FROM Estoque e
INNER JOIN ItemVenda iv ON iv.codProduto = e.codProduto
INNER JOIN Venda v ON v.codVenda = iv.codVenda
WHERE v.data BETWEEN e.Inicio AND e.Fim
GROUP BY e.codEstoque,
e.codProduto,
e.Inicio,
e.Fim,
e.Quantidade
Which DBMS? Is mysql or sql-server?
– user28595
is the sql-server.
– Jagunço
https://social.msdn.microsoft.com/Forums/pt-BR/477cc21d-083a-4df2-8bbf-4d3446d3710a/trigger-para-update-stock?forum=transactsqlpt such a common example is easy on Google and the like.
– Motta