SQL Server触发器无法正常工作

时间:2014-06-22 16:01:22

标签: sql sql-server events triggers

我有这2个触发器,没有人工作,但我不知道为什么,不是每个人都可以帮助我:

插入:

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

删除:

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

1 个答案:

答案 0 :(得分:0)

两个触发器都有2个缺陷。 SELECT语句未分配WHERE子句中使用的@IdVenda值。此外,这些触发器不适用于多行INSERT / UPDATE语句。我建议你加入INSERTED / DELETED,这将解决这两个问题。下面是一个示例,假设LinhasVenda表中的列名也称为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