使用触发器来获取GETDATE()

时间:2018-03-04 16:51:44

标签: sql sql-server triggers getdate

如果该列的值为null,我正在使用Trigger将Products表更新为当前日期。我还有一切,当我将新值插入表中时,DateAdded列为NULL而不是今天的当前日期。我不确定什么是错的,为什么它不起作用。任何帮助将不胜感激,谢谢!

IF OBJECT_ID('Products_INSERT') IS NOT NULL
DROP TRIGGER Products_INSERT

CREATE TRIGGER Products_INSERT
ON Products 
AFTER INSERT
AS
UPDATE Products
SET DateAdded = GETDATE()
WHERE DateAdded = NULL;

2 个答案:

答案 0 :(得分:5)

我希望触发器看起来像这样:

CREATE TRIGGER INSERT_Products ON Products 
AFTER INSERT
AS BEGIN
    UPDATE Products
        SET DateAdded = GETDATE()
        FROM Products p JOIN
             Inserted i
             ON p.productid = i.productid;
END;

如果您想测试insert

中未设置该值
CREATE TRIGGER INSERT_Products ON Products 
AFTER INSERT
AS BEGIN
    UPDATE Products
        SET DateAdded = GETDATE()
        FROM Products p JOIN
             Inserted i
             ON p.productid = i.productid
        WHERE DateAdded IS NOT NULL;
END;

那就是说,我只会使用默认值 -

create table Products (
    ProductId int identity primary key,
    . . . 
    DateAdded datetime not null default getdate()
);

比触发器简单得多,这仍然允许您使用自己的值覆盖默认值。

答案 1 :(得分:3)

null不是价值,而是缺乏价值。要对其进行检查,您需要使用is运算符,而不是=运算符:

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