SQL:如果字段值低于特定值则阻止更新

时间:2019-03-20 16:09:57

标签: sql constraints h2 flyway database-trigger

我想在表中添加一个约束:

create table asset (
   id number(19,0) not null,
    name varchar2(255 char),
    description varchar2(255 char),
    type varchar2(255 char),
    height number(10,0),
    width number(10,0),
    bytes blob,
    primary key (id)
);

将ID为0到8的资产存储在上面之后:

ALTER TABLE ASSET ADD CONSTRAINT check_if_id_bigger_than_eight CHECK (ID > 8)

为避免对ID从0到8的行进行进一步修改,不幸的是上述方法不起作用,因为不允许其数据违反约束,有没有简便的方法?

1 个答案:

答案 0 :(得分:0)

此触发器可能有效(SQL Server语法)

create trigger TR_8 
on asset
after insert, update

as
if exists(
 select * -- checks if new or modified datum has id between 0 and 8
 from inserted 
 where inserted.id between 0 and 8
)
begin
 RAISERROR ('Ids between 0 and 8 must stay untouched', 16, 10); --if so, rollback the transaction giving an error
 rollback transaction
end