您可以在以下条件下使用 CHECK 约束:
- starting_date > prenotation_date + 3
- 开始日期
- TRUNC(starting_date) = TRUNC(ending_date)
starting_date > prenotation_date + 3 将确保在预订 3 天后允许预订。
starting_date < ending_date 将确保预订的时间总是在离开时间之前。
TRUNC(starting_date) = TRUNC(ending_date) 将确保在同一天完成预订。 即预订窗口只有一天。
测试用例:
创建表
SQL> CREATE TABLE t(
2 prenotation_date DATE NOT NULL, starting_date DATE NOT NULL, ending_date DATE NOT NULL);
Table created.
SQL>
添加检查约束
SQL> ALTER TABLE t ADD CONSTRAINT t_chk CHECK(
2 (starting_date > prenotation_date + 3)
3 AND (starting_date < ending_date)
4 AND (TRUNC(starting_date) = TRUNC(ending_date))
5 );
Table altered.
SQL>
插入:检查starting_date > prenotation_date + 3。下面的插入应该会失败。
SQL> INSERT
2 INTO t VALUES
3 (
4 to_date('03/01/2015 00:00:00','mm/dd/yyyy hh24:mi:ss'),
5 to_date('03/02/2015 08:00:00','mm/dd/yyyy hh24:mi:ss'),
6 to_date('03/02/2015 10:00:00','mm/dd/yyyy hh24:mi:ss')
7 );
INSERT
*
ERROR at line 1:
ORA-02290: check constraint (LALIT.T_CHK) violated
SQL>
插入:检查开始日期
SQL> INSERT
2 INTO t VALUES
3 (
4 to_date('02/01/2015 00:00:00','mm/dd/yyyy hh24:mi:ss'),
5 to_date('03/02/2015 10:00:00','mm/dd/yyyy hh24:mi:ss'),
6 to_date('03/02/2015 08:00:00','mm/dd/yyyy hh24:mi:ss')
7 );
INSERT
*
ERROR at line 1:
ORA-02290: check constraint (LALIT.T_CHK) violated
SQL>
INSERT :检查预订在同一天完成。下面的插入应该失败。注意时间08:00:00 和10:00:00 分别表示开始和结束时间。
SQL> INSERT
2 INTO t VALUES
3 (
4 to_date('02/01/2015 00:00:00','mm/dd/yyyy hh24:mi:ss'),
5 to_date('03/02/2015 08:00:00','mm/dd/yyyy hh24:mi:ss'),
6 to_date('04/02/2015 10:00:00','mm/dd/yyyy hh24:mi:ss')
7 );
INSERT
*
ERROR at line 1:
ORA-02290: check constraint (LALIT.T_CHK) violated
SQL>
INSERT :所有值都满足要求,下面的插入应该通过。
SQL> INSERT
2 INTO t VALUES
3 (
4 to_date('02/01/2015 00:00:00','mm/dd/yyyy hh24:mi:ss'),
5 to_date('03/02/2015 08:00:00','mm/dd/yyyy hh24:mi:ss'),
6 to_date('03/02/2015 10:00:00','mm/dd/yyyy hh24:mi:ss')
7 );
1 row created.
SQL>