oracle 触发器异常
oracle trigger with exception
我有以下要求
`
我有 2 tables,而在 table 1 上插入或更新之前,我们需要检查具有以下条件的触发器 where id should not be null and id needs to exist in table 2 qid column and length of id should be greater than length 6
如果以上情况失败需要在同一个触发器中打印异常..
请帮我解决上面的问题
这不是触发器问题,而是各种约束:
- 外键会检查ID是否存在
NOT NULL
将确保它不为空
- check 约束将检查其长度(但这无关紧要,因为外键约束无论如何都会处理)
所以:
SQL> create table table2
2 (qid number constraint pk_2 primary key,
3 name varchar2(10));
Table created.
SQL> create table table1
2 (id1 number constraint pk_1 primary key,
3 id number constraint fk_12 references table2 (qid) not null,
4 name varchar2(10),
5 address varchar2(10),
6 --
7 constraint ch_len_id check (length(id) > 6) --> you can skip that
8 );
Table created.
SQL>
如果一定要触发,那么:
SQL> create or replace trigger trg_biu_t1
2 before insert or update on table1
3 for each row
4 declare
5 l_cnt number;
6 begin
7 if :new.id is null then
8 raise_application_error(-20000, 'ID can not be NULL');
9
10 elsif length(:new.id) <= 6 then
11 raise_application_error(-20001, 'ID length must be greater than 6');
12
13 else
14 select count(*)
15 into l_cnt
16 from table2
17 where qid = :new.id;
18
19 if l_cnt = 0 then
20 raise_application_error(-20002, 'ID does not exist in table2');
21 end if;
22 end if;
23 end trg_biu_t1;
24 /
Trigger created.
SQL>
我有以下要求
`
我有 2 tables,而在 table 1 上插入或更新之前,我们需要检查具有以下条件的触发器 where id should not be null and id needs to exist in table 2 qid column and length of id should be greater than length 6
如果以上情况失败需要在同一个触发器中打印异常..
请帮我解决上面的问题
这不是触发器问题,而是各种约束:
- 外键会检查ID是否存在
NOT NULL
将确保它不为空- check 约束将检查其长度(但这无关紧要,因为外键约束无论如何都会处理)
所以:
SQL> create table table2
2 (qid number constraint pk_2 primary key,
3 name varchar2(10));
Table created.
SQL> create table table1
2 (id1 number constraint pk_1 primary key,
3 id number constraint fk_12 references table2 (qid) not null,
4 name varchar2(10),
5 address varchar2(10),
6 --
7 constraint ch_len_id check (length(id) > 6) --> you can skip that
8 );
Table created.
SQL>
如果一定要触发,那么:
SQL> create or replace trigger trg_biu_t1
2 before insert or update on table1
3 for each row
4 declare
5 l_cnt number;
6 begin
7 if :new.id is null then
8 raise_application_error(-20000, 'ID can not be NULL');
9
10 elsif length(:new.id) <= 6 then
11 raise_application_error(-20001, 'ID length must be greater than 6');
12
13 else
14 select count(*)
15 into l_cnt
16 from table2
17 where qid = :new.id;
18
19 if l_cnt = 0 then
20 raise_application_error(-20002, 'ID does not exist in table2');
21 end if;
22 end if;
23 end trg_biu_t1;
24 /
Trigger created.
SQL>