I need to create a table for automobiles.
Each automobile has a year of manufacture. The year of manufacture must be between 2000 and the current year.
year_manufacture INTEGER CONSTRAINT nn_automobiles_year_manufacture NOT NULL
CONSTRAINT ck_automobiles_year_manufacture
CHECK ((year_manufacture>= 2000)AND(year_manufacture<= "current year")),
See if such a workaround helps.
Everything you've been already told stands. As you can't directly check the year against SYSDATE
, create another column - THIS_YEAR
- which won't be used anywhere in your code. It is automatically populated on each insert and gets current year.
Constraint (which can't be inline) then compares YEAR_MANUFACTURE
with THIS_YEAR
.
SQL> create table cars
2 (id number constraint pk_cars primary key,
3 name varchar2(20) not null,
4 this_year number(4) default extract (year from sysdate),
5 year_manufacture number(4),
6 --
7 constraint ch_year_manufacture check (year_manufacture between 2000 and this_year)
8 );
Table created.
SQL>
Testing:
SQL> -- OK - after 2000, before 2019 (which is the current year)
SQL> insert into cars (id, name, year_manufacture) values (1, 'BMW', 2005);
1 row created.
SQL> -- Wrong - before 2000
SQL> insert into cars (id, name, year_manufacture) values (2, 'Mercedes', 1998);
insert into cars (id, name, year_manufacture) values (2, 'Mercedes', 1998)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_YEAR_MANUFACTURE) violated
SQL> -- Wrong - after 2019 (which is the current year)
SQL> insert into cars (id, name, year_manufacture) values (3, 'Cooper', 2020);
insert into cars (id, name, year_manufacture) values (3, 'Cooper', 2020)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_YEAR_MANUFACTURE) violated
SQL> -- OK - current year
SQL> insert into cars (id, name, year_manufacture) values (4, 'Opel', 2019);
1 row created.
SQL>
SQL> select * from cars;
ID NAME THIS_YEAR YEAR_MANUFACTURE
---------- -------------------- ---------- ----------------
1 BMW 2019 2005
4 Opel 2019 2019
SQL>