我遇到一种情况,用户不允许输入重复的值。如果用户试图添加重复值,系统将在审核表中保存用户的详细信息。触发器就是用来做这个的。我的代码如下
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 NULL
或IS 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并将insert提交到审计表的过程。一切都是这样的:
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;
/
但是,又一次,为什么要麻烦呢?唯一性是这里的关键词。