How do I add a not null column and a check constraint in one line in Oracle 11g?

南笙酒味 提交于 2019-12-12 03:31:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!