0

我有一个 start_session 和 end_session。

我想确保 end_session 是 start_session 后 60 分钟的约束。

这可能吗,类似于以下内容

ALTER TABLE BOOKING_SESSION ADD CONSTRAINT SESSION_LENGHT CHECK (END_SESSION > START_SESSION + 60 MINUTES );

我得到了以下触发器来检查开始会话是否大于结束会话(感谢 Justin Cave)

CREATE OR REPLACE TRIGGER trg_check_dates
  BEFORE INSERT OR UPDATE ON BOOKING_SESSION
  FOR EACH ROW
BEGIN
  IF( :NEW.END_SESSION < :NEW.START_SESSION )
  THEN
    RAISE_APPLICATION_ERROR( -20001, 
          'Invalid: END_SESSION must be greater than START_SESSION = ' || 
          to_char( :NEW.START_SESSION, 'YYYY-MM-DD HH24:MI:SS' ));
  END IF;
 END;
 /

但是我需要一个确保结束会话在 start_session 之后一小时的那个

4

1 回答 1

2

以下是如何使用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_sessionend_session列是timestamp数据类型。如果您将它们声明为Date数据类型,则check约束的公式可能是:

(end_session - srtart_session) >= 1/24  
于 2012-11-21T05:22:03.840 回答