简体   繁体   English

如何将一组列限制为全为空或全为非空

[英]How to constrain a set of columns to all be NULL or all be NOT NULL

Lets say I have a table like so, 可以说我有一张这样的桌子,

id | first name | middle name | last name

Now, the name columns can be NULL , but if any of the three, for example, first name is NOT NULL , then all three must be NOT NULL . 现在, name列可以为NULL ,但是如果这三个first name任何一个(例如, first nameNOT NULL ,则所有三个first name都必须为NOT NULL

How can I enforce this in Oracle? 如何在Oracle中执行此操作?

You can write a check constraint with the logics you need. 您可以使用所需的逻辑编写检查约束。 For example: 例如:

alter table yourTable
  add constraint check_not_null check
    (   
        first_name  is not null and
        middle_name is not null and
        last_name   is not null
      OR
        first_name  is null and
        middle_name is null and
        last_name   is null
    );

Say, 说,

alter table your_table 
  add constraint set_of_column_chk
  check (nvl2(first_name, 1, 0) + nvl2(middle_name, 1, 0) + nvl2(last_name, 1, 0) in (0, 3));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM