gpt4 book ai didi

sql - 发生约束违反时如何调用触发器?

转载 作者:搜寻专家 更新时间:2023-10-30 23:28:16 24 4
gpt4 key购买 nike

我遇到了不允许用户输入重复值的情况。如果用户尝试添加重复值,系统会在审计表中保存用户的详细信息。触发器用于此。我的代码在下面

create or replace trigger tr_add_on_audit_table
before insert on lds_consultant
for each row
declare
uname varchar2(30);
begin
select username into uname from lds_consultant where username = :NEW.USERNAME;

if uname <> '' or uname <> null then
insert into audit_table values(null, null, 'nishan', 'insert', null, null, 'cmd', null, 'LDS_CONSULTANT', 'CONSULTANT_ID',null, null, null);
end if;
end;

但此代码不会将数据插入审计表。

我怎样才能做到这一点?

最佳答案

NULL不等于也不不同于任何东西。你应该使用 IS NULLIS NOT NULL , 不是 <>也不= .

像这样:

create or replace trigger tr_add_on_audit_table
before insert on lds_consultant
for each row
declare
uname varchar2(30);
begin
select username
into uname
from lds_consultant
where username = :NEW.USERNAME;

if uname is not null then --> this!
insert into audit_table
values(null, null, 'nishan', 'insert', null, null, 'cmd', null, 'LDS_CONSULTANT', 'CONSULTANT_ID',null, null, null);
end if;
exception
when no_data_found then
null;
end;

我包含了异常处理程序部分,以防 SELECT 不返回任何内容;如果不太可能,将其删除(或正确处理;我什么都不做(NULL;)。此外,如有必要,处理其他异常。

此外,我建议您为要插入的所有 列命名。今天,您知道什么值去哪里,但在一两个月后您就会忘记第三个值是什么 NULL值应该意味着。

此外,您说过不允许用户输入重复的值 - 好吧,这段代码不会让它发生。

最简单的选择是在 USERNAME 上创建一个唯一键约束列并让 Oracle 处理重复项。

如果你想自己做,你应该例如

raise_application_error(-20000, 'Duplicate username is not allowed);

但是,这不会保存您的 INSERT进入表格,因为一切都将回滚。为了解决这个问题,创建一个使用 pragma autonomous_transaction 的过程并将插入提交到审计表中。

一切看起来像这样:

create or replace procedure p_audit as
pragma autonomous_transaction;
begin
insert into audit_table
values(null, null, 'nishan', 'insert', null, null, 'cmd', null, 'LDS_CONSULTANT', 'CONSULTANT_ID',null, null, null);
commit;
end;
/
create or replace trigger tr_add_on_audit_table
before insert on lds_consultant
for each row
declare
uname varchar2(30);
begin
select username
into uname
from lds_consultant
where username = :NEW.USERNAME;

if uname is not null then
p_audit;
raise_application_error(-20000, 'Duplicates are not allowed')
end if;
exception
when no_data_found then
null;
end;
/

但是,再一次,何必呢?唯一性是这里的关键词。

关于sql - 发生约束违反时如何调用触发器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com