Oracle 约束/唯一索引:检查查询是否没有结果 - 然后您可以插入该行

Oracle constraint / unique index: check if the query has no result - then you can insert the line

为了限制单元格的范围,我以前做过类似的事情:

ALTER TABLE "CES"."NS_CES" ADD CONSTRAINT "CHECK_OVER_DIAPAZON" CHECK (
        (ID_NS_WORK != 1835 AND ID_NS_WORK != 1833) OR
        (ID_NS_WORK = 1835 and PNS BETWEEN 0 AND 100 and QNS BETWEEN -200 AND 10) OR
        (ID_NS_WORK = 1833 and PNS BETWEEN 0 AND 100 and QNS BETWEEN -200 AND 10)
    );

但现在我有不同的任务:添加约束,这将检查查询结果是否 return 任何值。

这是我的 select,它必须 return 没有值,我想创建它作为 table Training_rule:[=14= 的检查约束]

select type, training_list_id, element_id, request_code
from training_rule
where after_rule is null and after_group is null
group by type, training_list_id, element_id, request_code
having count(*) > 1;

像这样:

ALTER TABLE "CES"."TRAINING_RULE" ADD CONSTRAINT "CHEK_SELECT_HAS_NO_RESULT" CHECK (
    ^HAS NO RESULT^:
    [
    select type, training_list_id, element_id, request_code
        from training_rule
        where after_rule is null and after_group is null
        group by type, training_list_id, element_id, request_code
        having count(*) > 1;
    ]
)

谢谢

编辑 1

感谢 Gordon Linoff

create unique index idx_trainingrule_4 on TRAINING_RULE (
         type, training_list_id, element_id, request_code,
         (case when after_rule is null and after_group is null then null
               else name
          end)
        );

你不能那样做。 ADD CHECK CONSTRAINT:

  • A check constraint can NOT be defined on a SQL View.
  • The check constraint defined on a table must refer to only columns in that table. It can not refer to columns in other tables.
  • A check constraint can NOT include a SQL Subquery.
  • A check constraint can be defined in either a SQL CREATE TABLE statement or a SQL ALTER TABLE statement.

它之前工作的原因是因为您在语法上正确的列值上应用了约束。但后者的语法不正确,是不允许的。

我认为您可以使用条件唯一索引来做您想做的事。这假设您在 table (trainingrule_id) 中有一个从不为负的唯一 id 列:

create unique index idx_trainingrule_4 on (
         type, training_list_id, element_id, request_code,
         (case when after_rule is null and after_group is null then -1
               else trainingrule_id
          end)
        );