gpt4 book ai didi

sql - 在非空列上插入后触发

转载 作者:行者123 更新时间:2023-12-02 08:50:13 26 4
gpt4 key购买 nike

我有一个表,其中包含两个 not nullCreatedUpdated

我写了相应的触发器

ALTER TRIGGER [dbo].[tr_category_inserted] ON [dbo].[Category]
AFTER INSERT
AS
BEGIN
UPDATE Category
SET Created = GETDATE(), Updated = GETDATE()
FROM inserted
WHERE Category.ID = inserted.ID;
END

ALTER TRIGGER [dbo].[tr_category_updated] ON [dbo].[Category]
AFTER UPDATE
AS
BEGIN
UPDATE Category
SET Updated = GETDATE()
FROM inserted
inner join [dbo].[Category] c on c.ID = inserted.ID
END

但是如果我插入新行,则会收到错误

Cannot insert the value NULL into column 'Created', table 'Category'; column does not allow nulls. INSERT fails.

插入命令:

INSERT INTO [Category]([Name], [ShowInMenu], [Deleted])
VALUES ('category1', 0, 0)

如何编写此类触发器而不将这些列设置为允许为空?

最佳答案

像这样修改你的表:

ALTER TABLE yourTable MODIFY COLUMN updated timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
ALTER TABLE yourTable MODIFY COLUMN created timestamp DEFAULT 0;

将创建的列的默认值设置为 0。不幸的是,MySQL 不允许在一张表中存在两个具有默认 CURRENT_TIMESTAMP 的时间戳列。要克服这个问题,您只需将 NULL 值插入到 created 列中,两列都将具有当前时间戳。

INSERT INTO yourTable (col1, created) VALUES ('whatever', NULL);

或者您将默认值设置为有效时间戳,例如

ALTER TABLE yourTable MODIFY COLUMN created timestamp DEFAULT '1970-01-01 00:00:00';

并像这样修改你的触发器:

ALTER TRIGGER [dbo].[tr_category_inserted] ON [dbo].[Category]
AFTER INSERT
AS
BEGIN
UPDATE Category
SET Created = GETDATE()
/* FROM inserted */ /*don't know where you got that from, do you port from SQL Server?*/
WHERE Category.ID = NEW.ID;
END

关于sql - 在非空列上插入后触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14497233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com