如果该列的值为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
。
感谢任何帮助。
非常感谢提前!
答案 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);
我注意到触发器正在更新正在修改的同一个表,这通常会导致代码混乱。