以下是如何使用Check
约束来施加这种限制:
SQL> create table Tb_test(
2 id number not null primary key,
3 start_session timestamp,
4 end_session timestamp
5 )
6 ;
Table created
SQL>
SQL> alter table tb_test
2 add constraint CHK_SES_TIME
3 check ((end_session is null) or ((end_session - start_session) >= interval '1' hour))
4 ;
Table altered
-- data that is violate our constraint
SQL> insert into tb_test(id, start_session, end_session)
2 values(1, systimestamp, systimestamp)
3 ;
insert into tb_test(id, start_session, end_session)
values(1, systimestamp, systimestamp)
ORA-02290: check constraint (HR.CHK_SES_TIME) violated
-- valid data
SQL> insert into tb_test(id, start_session, end_session)
2 values(1, systimestamp, systimestamp + interval '1' hour)
3 ;
1 row inserted
-- only start session added, end_session is null.
SQL> insert into tb_test(id, start_session)
2 values(2, systimestamp)
3 ;
1 row inserted
SQL> commit;
Commit complete
-- updating end_session with data that violate check constraint
SQL> update tb_test
2 set end_session = systimestamp;
update tb_test
set end_session = systimestamp
ORA-02290: check constraint (HR.CHK_SES_TIME) violated
-- updating end_session with valid data
SQL> update tb_test
2 set end_session = systimestamp + interval '1' hour;
1 row updated
在上面的示例中start_session
,end_session
列是timestamp
数据类型。如果您将它们声明为Date
数据类型,则check
约束的公式可能是:
(end_session - srtart_session) >= 1/24