Oracle SQL 如果(不)满足条件,则强制列为空

Oracle SQL force a column to be null if (not) meeting a condition

我有一个 table status:

如果 status.status 字段的值不是 completed

,我希望每条记录的 completionDate 字段为空
alter table status
        add constraint ck_completion
                check ( 
                        -- status.completiondate's value should be null
                    -- if (Lower(status.status) != 'complete')
                );

因为如果状态未完成或未完成,则不应有完成日期。我该怎么做?

您可以创建一个 table 级别约束,如果状态未完成则只允许空值,而当状态完成时允许任何值。

alter table status add constraint ck_completion check (
    lower(status) = 'complete'
    or completiondate is null
    )

如果您不想在状态为完成时在完成日期中接受空值,请尝试以下操作:

alter table status add constraint ck_completion check (
    (
        lower(status) <> 'complete'
        and completiondate is null
        )
    or (
        lower(status) = 'complete'
        and completiondate is not null
        )
    )