Q:

SQL Server Trigger not Working

i have this 2 triggers and no one is working, but i dont know why, can´t everyone help me:
Insert:
CREATE TRIGGER [dbo].[afterInsert]

ON [dbo].[LinhasVenda]

FOR INSERT

AS

BEGIN
    DECLARE
        @IdVenda INT,
        @PrecoTotalSIva MONEY,
        @PrecoTotalCIva MONEY
    SELECT
        @PrecoTotalSIva = PrecoTotalSIva,
        @PrecoTotalCIva = PrecoTotalCIva
    FROM
        INSERTED
    UPDATE Vendas SET ValorSIva = ValorSIva + @PrecoTotalSIva,
    ValorCIva = ValorCIva + @PrecoTotalCIva WHERE
    IdVenda = @IdVenda
END

Delete:
CREATE TRIGGER afterDelete

ON LinhasVenda

FOR DELETE
AS
BEGIN
    DECLARE
        @IdVenda INT,
        @IdArtifo INT,
        @PrecoTotalSIva MONEY,
        @PrecoTotalCIva MONEY

    SELECT
        @PrecoTotalSIva = PrecoTotalSIva,
        @PrecoTotalCIva = PrecoTotalCIva
    FROM
        DELETED

    UPDATE Vendas SET ValorSIva = ValorSIva - @PrecoTotalSIva,
    ValorCIva = ValorCIva - @PrecoTotalCIva WHERE
    IdVenda = @IdVenda
END

A:

Both triggers have 2 flaws.  The @IdVenda value used in the WHERE clause is not being assigned by the SELECT statements.  Also, these triggers will not work with multi-row INSERT/UPDATE statements.  I suggest you JOIN to INSERTED/DELETED, which will address both these problems.  Below is an example, assuming the column name in the LinhasVenda table is also named IdVenda.
CREATE TRIGGER [dbo].[afterInsert]
ON [dbo].[LinhasVenda]
FOR INSERT
AS
BEGIN 

UPDATE v
SET
      ValorSIva = v.ValorSIva + i.PrecoTotalSIva
    , ValorCIva = v.ValorCIva + i.PrecoTotalCIva 
FROM Vendas AS v
JOIN INSERTED AS i ON
    i.IdVenda = v.IdVenda;

END;
GO

CREATE TRIGGER afterDelete
ON LinhasVenda 
FOR DELETE 
AS 
BEGIN

UPDATE v
SET
      ValorSIva = v.ValorSIva - d.PrecoTotalSIva
    , ValorCIva = v.ValorCIva - d.PrecoTotalCIva 
FROM Vendas AS v
JOIN DELETED AS d ON
    d.IdVenda = v.IdVenda;
END;
GO

