比较:使用触发器插入的新值
Comparing :new value inserted with a trigger
我正在尝试构建一个触发器来检查要插入的行是否存在于另一个 table。
基本上我的2 table共享一栏,ID。
当新行在另一个 table.
中至少不存在一次时,我想阻止插入
我有这个:
create or replace trigger BIM
before insert on TABLE1
for each row
begin
if not exists (select 1 from TABLE2 where TABLE2.ID = :new.TABLE1.ID)
then
raise_application_error(-20634, 'Error');
end if;
end;
但我明白了:
PLS-00049: bad bind variable 'NEW.TABLE1'
您不需要重复table姓名:
create or replace trigger BIM
before insert on TABLE1
for each row
begin
if (select 1 from TABLE2 where TABLE2.ID = :new.ID and rownum = 0) is not null
then
raise_application_error(-20634, 'Error');
end if;
end;
也就是说,这是一个奇怪的要求。我建议您使用外键约束,但您明确表示 "at least once"。这让我怀疑您的数据模型不好——您缺少某种实体,其中 id
将是 table.
的主键
Gordon 是对的,在这种情况下最好使用外键约束。
您的代码的问题(除了 Gordon 指出的错误外)与 Postgres 等少数其他 DBMS 不同,在 Oracle 中,您不能在 PL/SQL [=21= 中使用 EXISTS
]喜欢IF
。它应该是一个纯粹的 SQL 语句。
create or replace trigger BIM
before insert on TABLE1
for each row
declare
l_id_exists INT;
begin
select CASE WHEN
exists (select 1 from TABLE2 where TABLE2.ID = :new.ID)
THEN 1
ELSE 0 END INTO l_id_exists from dual;
if l_id_exists = 0
then
raise_application_error(-20634, 'Error');
end if;
end;
/
我正在尝试构建一个触发器来检查要插入的行是否存在于另一个 table。
基本上我的2 table共享一栏,ID。 当新行在另一个 table.
中至少不存在一次时,我想阻止插入我有这个:
create or replace trigger BIM
before insert on TABLE1
for each row
begin
if not exists (select 1 from TABLE2 where TABLE2.ID = :new.TABLE1.ID)
then
raise_application_error(-20634, 'Error');
end if;
end;
但我明白了:
PLS-00049: bad bind variable 'NEW.TABLE1'
您不需要重复table姓名:
create or replace trigger BIM
before insert on TABLE1
for each row
begin
if (select 1 from TABLE2 where TABLE2.ID = :new.ID and rownum = 0) is not null
then
raise_application_error(-20634, 'Error');
end if;
end;
也就是说,这是一个奇怪的要求。我建议您使用外键约束,但您明确表示 "at least once"。这让我怀疑您的数据模型不好——您缺少某种实体,其中 id
将是 table.
Gordon 是对的,在这种情况下最好使用外键约束。
您的代码的问题(除了 Gordon 指出的错误外)与 Postgres 等少数其他 DBMS 不同,在 Oracle 中,您不能在 PL/SQL [=21= 中使用 EXISTS
]喜欢IF
。它应该是一个纯粹的 SQL 语句。
create or replace trigger BIM
before insert on TABLE1
for each row
declare
l_id_exists INT;
begin
select CASE WHEN
exists (select 1 from TABLE2 where TABLE2.ID = :new.ID)
THEN 1
ELSE 0 END INTO l_id_exists from dual;
if l_id_exists = 0
then
raise_application_error(-20634, 'Error');
end if;
end;
/