[英]Oracle Constraint Date Check SQL
我想在表上添加约束,以防止基于某些条件插入/更新记录。
更具体地说,如果插入或更新了一条记录,则两个日期字段中的年份必须相同,如果active为“ Y”
create table MY_TABLE
(
id NUMBER not null,
active CHAR(1) ,
date_one DATE,
date_two DATE
)
/* Allowed : both dates are 2014 AND flag id 'Y'*/
insert into MY_TABLE(id, active, date_one, date_two)
VALUES (1, 'Y', to_date('20141201', 'yyyymmdd') , to_date('20140101', 'yyyymmdd');
/* DISAllowed : dates have different year AND flag id 'Y'*/
insert into MY_TABLE(id, active, date_one, date_two)
VALUES (2, 'Y', to_date('20151201', 'yyyymmdd') , to_date('20140101', 'yyyymmdd');
/* Allowed : dates have different year AND flag id is NOT 'Y'*/
insert into MY_TABLE(id, active, date_one, date_two)
VALUES (3, 'N', to_date('20151201', 'yyyymmdd') , to_date('20140101', 'yyyymmdd');
非常感谢
添加约束是制定一些逻辑的问题,这些逻辑可以准确定义您要实现的业务逻辑。 在您的情况下,您希望ACTIVE
为N
或日期中的年份必须相同。
您可以使用EXTRACT()
函数来检查年份。 即
SQL> select extract(year from sysdate) from dual;
EXTRACT(YEARFROMSYSDATE)
------------------------
2015
这使您的条件active = 'N' or extract(year from date_one) = extract(year from date_two)
,然后可以在表DDL中声明:
create table my_table (
id number not null
, active char(1)
, date_one date
, date_two date
, constraint chk_dates check (
active = 'N' or extract(year from date_one) = extract(year from date_two) )
);
这将为您提供所需的结果:
SQL> insert into MY_TABLE(id, active, date_one, date_two)
2 VALUES (1, 'Y', to_date('20141201', 'yyyymmdd') , to_date('20140101', 'yyyymmdd'));
1 row created.
SQL> insert into MY_TABLE(id, active, date_one, date_two)
2 VALUES (2, 'Y', to_date('20151201', 'yyyymmdd') , to_date('20140101', 'yyyymmdd'));
insert into MY_TABLE(id, active, date_one, date_two)
*
ERROR at line 1:
ORA-02290: check constraint (REF.CHK_DATES) violated
SQL> insert into MY_TABLE(id, active, date_one, date_two)
2 VALUES (3, 'N', to_date('20151201', 'yyyymmdd') , to_date('20140101', 'yyyymmdd'));
1 row created.
我还将在ACTIVE
列上添加单独的约束,以确保它只能具有正确的值并在主键上
create table my_table (
id number not null
, active char(1)
, date_one date
, date_two date
, constraint pk_my_table primary key (id)
, constraint chk_my_table_active check ( active in ('Y', 'N') )
, constraint chk_dates check (
active = 'N' or extract(year from date_one) = extract(year from date_two) )
);
如果您ACTIVE
列可以有比Y或N多个值,那么你需要改变约束稍微考虑到这一点; 例如类似以下内容:
coalesce(active, 'X') <> 'Y' or extract(year from date_one) = extract(year from date_two)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.