0

我在 Oracle SQL Developer 中有两个简单的表(Train 和 Driver),每个表都有一个共同的属性(driverid)。本质上,我想要做的是不允许对驱动程序表中的特定驱动程序元组进行任何更新,如果它们的 driverid 属性存在于火车表中。我试图添加以下约束,但它会抛出“此处不允许子查询”的错误。

alter table driver add constraint drivcheck CHECK 
 (NOT EXISTS(select driverid from train))

我做了一些挖掘,总体感觉是应该用触发器检查这种情况,所以我试图创建一个触发器来完成这项工作,但没有取得很大成功。下面的触发器是我已经想出的。

create trigger drivcheck4
before update on driver
for each row
begin
declare
cursor dri is
select driverid from train where 'N' IN  
          (select availability 
           from driver 
           inner join train on    driver.driverid=train.driverid
           );
dri2 NUMBER;
begin
open dri;
loop
fetch dri into dri2;
exit when dri%NOTFOUND;
if check (exists (select * from dri2)) THEN
//Throw Error Section
else
//Allow update operation to take place
end if;
end loop;
close dri;
end;

我知道触发器可能执行的操作可能与描述的不同,但这只是我实验的结果。我最初的描述是我想要达到的目标。如果有人有任何想法,我将不胜感激!

4

1 回答 1

0

安德鲁,

您是否面临任何错误?以下内容应该可以工作。如果您也可以发布一些示例数据,那将很容易测试。

    create or replace trigger trg_bu_driver2
    before update on driver
    for each row
    declare
      l_cnt number;
    begin
    select count(*)
    into   l_cnt
    from   train
    where  driver_id = :new.driver_id;
    if (l_cnt > 0) then
       raise_application_error (-20001, 'new driver id exists in train table');
    end if;
    end trg_bu_driver2;
    /

测试:

    SQL> select * from driver;

     DRIVER_ID COLUMN2
    ---------- --------------------
            10 driver1

    SQL> select * from train;

     DRIVER_ID   TRAIN_ID COLUMN3
    ---------- ---------- --------------------
            20        100 train1
  • 更新到火车表中不存在的驱动程序 ID。

      1  update driver
      2  set    driver_id = 30
      3* where  driver_id = 10
    SQL> /
    
    1 row updated.
    
    No issues.
    
    SQL> rollback;
    
    Rollback complete.
    

--更新到存在于列车表中的驱动程序 ID 会引发错误。

    SQL> update driver
      2  set    driver_id = 20
      3  where  driver_id = 10
      4  ;
    update driver
           *
    ERROR at line 1:
    ORA-20001: new driver id exists in train table
    ORA-06512: at "DMART_ETL.TRG_BU_DRIVER2", line 9
    ORA-04088: error during execution of trigger 'DMART_ETL.TRG_BU_DRIVER2'
于 2013-04-12T01:03:11.533 回答