ORACLE Constraint to allow Null Value, IF

2020-07-22 18:54发布

问题:

I'm working with oracle for the first time, and I have a table called ExpenseReport which stores details about expenses.

I want Nulls to be allowed for ApprUserNo IF ERStatus = 'PENDING' Any help would be greatly appreciated, I've been trying to sort this all morning

CREATE TABLE ExpenseReport 
(
  ERNo           NUMBER(10) NOT NULL,
  ERDesc         VARCHAR2(255) NOT NULL,
  ERSubmitDate   DATE NOT NULL,
  ERStatusDate   DATE NOT NULL,
  ERStatus       VARCHAR2(8) DEFAULT 'PENDING' NOT NULL,
  SubmitUserNo   NUMBER(10) NOT NULL,
  ApprUserNo     NUMBER(10) NOT NULL CONSTRAINT BEN_Check CHECK (ERStatus LIKE('PENDING')),
  UsersUserNo    NUMBER(10) NOT NULL,
  AssetAssetNo   NUMBER(10) NOT NULL,
  PRIMARY KEY (ERNo),
  CONSTRAINT Check_ER_Date CHECK (ERStatusDate >= ERSubmitDate),
  CONSTRAINT ERStatus_Null_Exception CHECK (IF ERStatus = 'PENDING',AppUserNo = NULLABLE),
  CONSTRAINT ERStatus_Option CHECK (ERStatus = 'PENDING','APPROBED','DENIED')
)

回答1:

You need to re-form your constraints.

First, if you ever want a field to hold nulls, regardless of any other rules, it must be a nullable field.

ApprUserNo     NUMBER(10)   NULL,   -- No Check Constrain

Second, create a constraint that says ApprUserNo can not be NULL, unless ErStatus = 'PENDING'

CONSTRAINT ERStatus_Null_Exception CHECK (AppUserNo IS NOT NULL OR ERStatus = 'PENDING'),


回答2:

This should do it:

CONSTRAINT ERStatus_Null_Exception 
     CHECK (ERStatus <> 'PENDING' AND AppUserNo IS NOT NULL)


You should also change:
CONSTRAINT BEN_Check CHECK (ERStatus LIKE('PENDING'))
to
CONSTRAINT BEN_Check CHECK (ERStatus = 'PENDING')
because a) LIKE is not a function and b) LIKE without wildcards does not make sense.

Then you have another error here:
CONSTRAINT ERStatus_Option CHECK (ERStatus = 'PENDING','APPROBED','DENIED')
that should be
CONSTRAINT ERStatus_Option CHECK (ERStatus IN ('PENDING','APPROBED','DENIED'))

Please re-read the chapter in the Oracle manual that documents the syntax for CREATE TABLE and SQL conditions.