2011-12-02 75 views
0

我想检查输入的时间,以确定是否在已存储的任何其他约会的2小时内。Oracle触发器 - 检查已有数据

我的表测试(ID,数量& testdate,时间戳)

我有检查,看看新的时间是否为2小时的时间内触发我指定

create or replace trigger "TEST_T1" 
BEFORE 
insert on "TEST" 
for each row 
when (new.testdate is not null) 
begin 
    if (:new.testdate BETWEEN (to_timestamp('12-AUG-12 02:00:00PM') - interval '120' minute) 
         AND (to_timestamp('12-AUG-12 02:00:00PM') + interval '120' minute)) 
    then raise_application_error(-20634, 'This time clashes with another event.'); 
    end if; 
end; 

是有可能取代这次我从数据库中列出的时间列表?

与米哈尔Powaga帮助 - 下面 - 我设法得到这种使用

create or replace trigger "TEST_T1" 
BEFORE 
insert on "TEST" 
for each row 
when (new.testdate is not null) 
begin 
    DECLARE l_exists INTEGER; 
    BEGIN 
     SELECT COUNT(*) INTO l_exists FROM test WHERE testdate BETWEEN :new.testdate - interval '120' minute AND :new.testdate + interval '120' minute AND ROWNUM = 1; 
     IF l_exists = 1 THEN raise_application_error(-20634, 'This time clashes with another event.'); 
     END IF; 
    END; 
END; 
+0

此触发器不能防止:a)可能会将TESTDATE更改为时间冲突的更新与另一个或者b)同时插入(在单独的事务中),这些插入彼此冲突。一个更简单和更健壮的方法(不使用触发器)可能会将主键约束TESTDATE与检查约束强制为120分钟的倍数。 –

回答

1
create or replace trigger "TEST_T1" 
BEFORE 
insert on "TEST" 
for each row 
when (new.testdate is not null) 
begin 
    declare qty integer := 0; 
    begin 
     select count(*) into qty from test where testdate between (:new.testdate - 2/24) and (:new.testdate + 2/24) and rownum = 1; 
     if qty > 0 then 
      raise_application_error(-20634, 'This time clashes with another event.'); 
     end if; 
    end; 
end; 

PS工作。请注意,我不是Oracle开发人员,因此可能有错误,但我认为这是要走的路:-)

+0

感谢您的帮助 - 它让我走上了正确的路线。不能使用存在那里,所以这是我做过什么 '创建或“TEST” 替换触发“TEST_T1” 前 插入每一行 时(new.testdate不为null) 开始 DECLARE l_exists INTEGER; BEGIN SELECT COUNT(*)INTO l_exists FROM测试 WHERE testdate BETWEEN:new.testdate - 间隔 '120' 分钟AND:new.testdate +间隔 '120' 分钟 AND ROWNUM = 1; IF l_exists = 1 THEN raise_application_error(-20634,'This time clashes with another event。'); END IF; END; 结束;' – Edward

+0

请检查修正版本。 –

+0

冒牌货不 - 2个错误 '3 PLS-00103:出现符号 “SELECT” 在需要下列之一时:开始功能编译程序亚型型电流CURSO PLS-00103:出现符号“期末文件”当期待以下其中一种情况时:(开始case声明结束异常退出goto if循环mod null编译指示提升返回select更新while' – Edward