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