保护列,禁止更新,仅当 MySQL 中为 NULL 时才允许插入

ref*_*xiv 5 mysql

我想保护日期列中的现有日期不被覆盖。因此,不允许更新日期列,并且仅当现有字段值为 NULL(日期列默认值为 NULL)时才允许插入。是触发器在MySQL中做到这一点的唯一途径?如果是这样,下面的触发器会起作用吗?

create trigger date_check
before insert, update on date
for each row
begin
if(date IS NOT NULL) then
 SIGNAL 'date already set'
end if ;
end ;
Run Code Online (Sandbox Code Playgroud)

背景:我有一个包含由于用户错误而意外更改的关键日期的表格。我在用户界面中进行了一些检查以防止这种情况再次发生,但如果可能的话,我希望直接与数据库一起使用另一层安全性。

Gor*_*off 5

是的,在 MySQL 中触发器是执行此操作的唯一方法。MySQL 不支持约束。

你的触发器不完全正确。首先,你有update on date,但这应该是update on <table name>其次,您正在检查用于更新的日期值。也许你的意思是:

create trigger date_check_update
before update on <the table name goes here>
for each row
begin
    if (old.date IS NOT NULL) then
        SIGNAL 'date already set'
    end if ;
end;
Run Code Online (Sandbox Code Playgroud)

在这种情况下触发insert是没有意义的。