2016-07-08 159 views
1

我是新来的SQL Server,我试图构建一个简单的更新触发器,只要将列ceu_amount从零更新为任何数字比零。SQL Server INSERT在后更新触发器

从使用PRINT语句,我知道变量包含正确的值来执行INSERT语句,但没有行被插入。

你能帮忙吗?

CREATE TRIGGER [dbo].[TRG_Product_Function_Modified] ON [dbo].[Product_Function] 
AFTER UPDATE 
AS 
BEGIN 
SET NOCOUNT ON; 

    -- 
    -- Variable definitions 
    -- 
    DECLARE @product_code_new as varchar(31) 
    DECLARE @product_code_old as varchar(31) 

    -- 
    -- Check if the staging table needs to be updated. 
    -- 
    SELECT @product_code_new = product_code FROM Inserted where ISNULL(ceu_amount,0) > 0; 
    SELECT @product_code_old = product_code FROM Deleted where ISNULL(ceu_amount,0) = 0; 
     IF @product_code_new IS NOT NULL 
     AND @product_code_old IS NOT NULL 
      INSERT INTO Product_Function_Staging VALUES (@product_code_new,CURRENT_TIMESTAMP); 

END; 

回答

-2

尝试使用此

CREATE TRIGGER [dbo].[Customer_UPDATE] 
     ON [dbo].[Customers] 
AFTER UPDATE 
AS 
BEGIN 
     SET NOCOUNT ON; 

     DECLARE @CustomerId INT 
     DECLARE @Action VARCHAR(50) 

     SELECT @CustomerId = INSERTED.CustomerId  
     FROM INSERTED 

     IF UPDATE(Name) 
     BEGIN 
       SET @Action = 'Updated Name' 
     END 

     IF UPDATE(Country) 
     BEGIN 
       SET @Action = 'Updated Country' 
     END 

     INSERT INTO CustomerLogs 
     VALUES(@CustomerId, @Action) 
END 
+0

我建议编辑它,使其引用OPs表和列。另外,如果更新不关心更新的价值,只是列的设置,所以我不认为这将工作无论如何。 –

0

这部分代码看起来可疑我..

SELECT @product_code_new = product_code FROM Inserted where ISNULL(ceu_amount,0) > 0; 
    SELECT @product_code_old = product_code FROM Deleted where ISNULL(ceu_amount,0) = 0; 
     IF @product_code_new IS NOT NULL 
     AND @product_code_old IS NOT NULL 
      INSERT INTO Product_Function_Staging VALUES (@product_code_new,CURRENT_TIMESTAMP); 

以上将正常工作,如果只有一个行更新,如果有什么有多个值.. product_code将默认为上一个值

您可以将上面的代码部分更改为低

Insert into Product_Function_Staging 
select product_code ,CURRENT_TIMESTAMP from inserted where product_code is not null 
+0

感谢您的提示......它的工作! – Bing

0

如果有多于一行的数据更新为ceu_amount> 0,您将获得@product_code_new的未定值;类似的@product_code_old如果多于一行用ceu_amount NULL更新或等于0. 您可以发布一些示例数据吗?

0

我不会在触发器中使用类似这样的变量,因为触发器的原因可能是更新到多行,此时您的更新和删除表中会有多行。

我认为我们可以更安全,更有效地使此插入一个简单的查询,但我假设你有一个独特的密钥才能使用:

CREATE TRIGGER [dbo].[TRG_Product_Function_Modified] ON [dbo].[Product_Function] 
AFTER UPDATE 
AS 
BEGIN 
    SET NOCOUNT ON; 

    INSERT INTO Product_Function_Staging 
    SELECT i.product_code, CURRENT_TIMESTAMP 
    FROM inserted i 
     JOIN deleted d ON i.product_code = d.product_code -- assuming product_code is unique 
    WHERE i.ceu_amount > 0 -- new value > 0 
     AND ISNULL(d.ceu_amount, 0) = 0; -- old value null or 0 
END; 

我不知道,你需要检查对于数据中的空值,所以我在where子句中做了一个最佳猜测。