我在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;
我知道触发器可能正在执行与描述不同的其他操作,但这只是我试验的结果。我最初的描述是我想要实现的。如果有人有任何想法,我将非常感激!
答案 0 :(得分: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'