问题
I'm trying to add a new INTEGER column to a table. The column must be NOT NULL, with a default value of 1, and only accept values greater than zero.
I'm trying to do this at the moment:
ALTER TABLE FOO_AUTHORS
ADD PUBLICATION_PERIOD_DAYS INTEGER DEFAULT(1) NOT NULL
CONSTRAINT publicationPeriodDays
CHECK (PUBLICATION_PERIOD_DAYS>0);
Is there a way to do this in one line? I'm following this example, but it's not working because of the NOT NULL. Is the NOT NULL then necessary?
I'm getting the following error from the DB:
QL Error: ORA-02293: cannot validate (DBOWNER.PUBLICATIONPERIODDAYS) - check constraint violated 02293. 00000 - "cannot validate (%s.%s) - check constraint violated" *Cause: an alter table operation tried to validate a check constraint to populated table that had nocomplying values.
If I try it without the NOT NULL, it works fine.
回答1:
Roll the NOT NULL constraint into the CHECK constraint:
ALTER TABLE FOO_AUTHORS
ADD PUBLICATION_PERIOD_DAYS INTEGER DEFAULT 1
CONSTRAINT publicationPeriodDays
CHECK ( PUBLICATION_PERIOD_DAYS IS NOT NULL AND PUBLICATION_PERIOD_DAYS > 0 );
The existing rows will have their PUBLICATION_PERIOD_DAYS set to the default value.
来源:https://stackoverflow.com/questions/42671008/how-do-i-add-a-not-null-column-and-a-check-constraint-in-one-line-in-oracle-11g