使用SQL分配时间表

问题描述 投票:3回答:1

我的数据库中有这两个表:

Session(startTime,endTime,date) 

Allocation(startTime,endTime,date)

时间表中已经存在会话,我需要以所有会话之间不存在混淆的方式分配新会话。我想到了类似的东西:

ALTER TABLE allocation ADD CONSTRAINT timeC 
  check (startTime not between (select startTime from session) 
                           and (select endTime from session)) 

问题是不可能这样做,因为我们不能将关键字“between”用于两组值(与endTime相同)。

如何设置添加此约束? (我用的是Oracle 11g)

sql oracle11g
1个回答
1
投票

这不能通过检查约束来完成;然而,触发器可能有所帮助(正如戈登已经说过的那样)。这是一个例子:

SQL> create table tsession
  2    (id        number  constraint pk_tsess primary key,
  3     starttime date,
  4     endtime   date);

Table created.

SQL>
SQL> create table tallocation
  2    (id        number  constraint fk_all_sess references tsession (id),
  3     starttime date,
  4     endtime   date);

Table created.

SQL>
SQL> create or replace trigger trg_biu_all
  2    before insert or update on tallocation
  3    for each row
  4  declare
  5    l_dummy varchar2(1);
  6  begin
  7    select 'x'
  8      into l_dummy
  9      from tsession s
 10      where s.id = :new.id
 11        and :new.starttime between s.starttime and s.endtime;
 12
 13    raise_application_error(-20001, 'Can not set such a start time as it collides with TSESSION values');
 14  exception
 15    when no_data_found then
 16      -- OK, no problem - no collision
 17      null;
 18  end;
 19  /

Trigger created.

现在,测试:

SQL> -- Insert master record, ID = 1; it'll take whole February
SQL> insert into tsession values (1, date '2018-02-01', date '2018-02-28');

1 row created.

SQL> -- I don't want to allow this date to "jump in" between 2018-02-01 and 2018-02-28
SQL> insert into tallocation (id, starttime) values (1, date '2018-02-13');
insert into tallocation (id, starttime) values (1, date '2018-02-13')
            *
ERROR at line 1:
ORA-20001: Can not set such a start time as it collides with TSESSION values
ORA-06512: at "HR.TRG_BIU_ALL", line 10
ORA-04088: error during execution of trigger 'HR.TRG_BIU_ALL'


SQL> -- This one should be OK, as it is in March
SQL> insert into tallocation (id, starttime) values (1, date '2018-03-22');

1 row created.

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.