【问题标题】:Sql: prevent update if field value below certain valueSql:如果字段值低于某个值,则阻止更新
【发布时间】:2019-08-11 10:02:39
【问题描述】:

我想给我的表添加一个约束:

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 的行,不幸的是,上面的方法不起作用,因为它不允许有违反约束的数据,有没有简单的方法来做到这一点?

【问题讨论】:

  • 您需要通过触发器来执行此操作。约束是在一行内的值上。这不是关于是否可以更新值的是/否标志。
  • H2 仅支持用 Java 编写的触发器。你不能在 SQL 中定义它们

标签: sql constraints h2 flyway database-trigger


【解决方案1】:

此触发器可能有效(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

【讨论】:

  • 谢谢,这实际上不适用于H2,你知道如何更正H2的语法吗?
  • 对不起,我从未使用过 H2。无论如何,我建议您在问题中添加 H2 标签
猜你喜欢
  • 1970-01-01
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 2014-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多