Drop Inventory with SQL Triggers

Asked

Viewed 610 times

1

I started doing a course on SQL and I’m in doubt about triggers this is the table

create table Produto (
    codProduto int primary key identity(1,1),
    Nome varchar(50),
    Quantidade int,
    Preco smallmoney
);
create table ItemVenda (
    codVenda int identity(1,1),
    foreign key (codProduto) references Produto(codProduto),
    codProduto int primary key,
    Quantidade int
);

I need to make a Trigger so that after I give Insert in the product sales table is debited the quantity inserted in the product table, as I could do this?

  • Which DBMS? Is mysql or sql-server?

  • is the sql-server.

  • 1

    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.

1 answer

3


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.