SQL Server 2012 AFTER INSERT触发器将null值替换为当前日期

时间:2014-05-12 04:22:23

标签: sql sql-server triggers sql-insert

如果该列的值为DateAdded,我需要创建一个触发器,插入Products表的null列的当前日期。

这是我尝试过的:

Use MyGuitarShop;
IF OBJECT_ID ('Products_INSERT') IS NOT NULL
    DROP TRIGGER Products_INSERT;
GO

CREATE TRIGGER Products_INSERT
    ON Products
    AFTER INSERT
AS
    UPDATE Products
    SET DateAdded = GETDATE()
    WHERE DateAdded IS NULL
        AND DateAdded IN (SELECT DateAdded FROM inserted);
GO

为了测试这个,我运行了以下INSERT语句:

INSERT INTO Products
VALUES (4, 'AK-5300', 'Awesome Keyboard 5300',
        'This keyboard is so awesome, you just might freak!',
        699.99, 30.00, NULL)

运行INSERT语句后,DateAdded列仍然显示NULL

感谢任何帮助。

非常感谢提前!

1 个答案:

答案 0 :(得分:1)

您的方法不是正确的方法。您应该只使用DateAdded的默认值。但是,这个查询的问题是:

UPDATE Products
SET DateAdded = GETDATE()
WHERE DateAdded IS NULL
    AND DateAdded IN (SELECT DateAdded FROM inserted);

这两个条件是不相容的吗?你有DataAdded IS NULL罚款。那是真实的。但几乎与NULL的任何比较都是错误的,包括IN比较。所以对于你想要做的事情,这应该足够了:

UPDATE Products
SET DateAdded = GETDATE()
WHERE DateAdded IS NULL;

你可以写:

UPDATE Products
SET DateAdded = GETDATE()
WHERE DateAdded IS NULL OR
      DateAdded IN (SELECT DateAdded FROM inserted);

我注意到触发器正在更新正在修改的同一个表,这通常会导致代码混乱。