触发执行

时间:2014-04-27 16:17:25

标签: sql-server triggers

我有一张桌子,每个项目的价格不同。每个项目的价格都是0,1,2,3。我需要在价格0改变时更改价格3。价格3 =价格0 + 20%。我做了这个触发器:

CREATE TRIGGER trg_PG_Change_Price3

ON ItemSellingPrices

AFTER UPDATE

AS

BEGIN

DECLARE
    @Item NVARCHAR(25),
    @CostPrice FLOAT;

SELECT
    @Item = ItemID,
    @CostPrice = UnitPrice
FROM
    inserted
WHERE PriceLineID = 0

UPDATE ItemSellingPrices
SET     UnitPrice = @CostPrice*1.2
WHERE ItemID = @Item AND PriceLineID = 3

END

事实证明,当我通过SQL查询直接运行UPDATE时,一切都运行良好。但是当价格0通过ERP更新时没有任何反应。有人有主意吗? (MS SQL Server) 当通过ERP系统完成更新时,触发器似乎不会触发。

1 个答案:

答案 0 :(得分:0)

CREATE TRIGGER trg_PG_Change_Price3
ON ItemSellingPrices
AFTER UPDATE
AS
BEGIN
 SET NOCOUNT ON;

    SELECT i.ItemID, i.UnitPrice INTO #temp
    FROM inserted i INNER JOIN deleted d 
    ON i.ItemID = d.ItemID
    WHERE i.PriceLineID = 0
    AND   i.UnitPrice <> d.UnitPrice


    UPDATE T
    SET T.UnitPrice = i.UnitPrice * 1.2
    FROM ItemSellingPrices T INNER JOIN #temp i
    ON T.ItemID = i.ItemID
    WHERE T.PriceLineID = 3

END

没有临时表

CREATE TRIGGER trg_PG_Change_Price3
ON ItemSellingPrices
AFTER UPDATE
AS
BEGIN
 SET NOCOUNT ON;

    UPDATE T
    SET T.UnitPrice = i.UnitPrice * 1.2
    FROM ItemSellingPrices T 
            INNER JOIN (    SELECT i.ItemID, i.UnitPrice
                            FROM inserted i INNER JOIN deleted d 
                            ON i.ItemID = d.ItemID
                            WHERE i.PriceLineID = 0
                            AND   i.UnitPrice <> d.UnitPrice
                        ) i
    ON T.ItemID = i.ItemID
    WHERE T.PriceLineID = 3

END