Oracle触发器基础
old new
--- INSERT
DELETE ---
UPDATE UPDATE
【注】触发器中有两个非常重要的逻辑表,old表和new表,这个表只有在操纵触发器的时候才能接触到,old表和new表只能在行级触 发器中使用,在语句级触发器中是不支持的。
CREATE OR REPLACE TRIGGER del_dept
AFTER DELETE ON dept
FOR EACH ROW
BEGIN
DELETE FROM emp WHERE id = :old.id;
END del_dept;
DELETE FROM dept WHERE id = '01';
CREATE OR REPLACE TRIGGER insert_dept
after INSERT ON dept
FOR EACH ROW
BEGIN
INSERT INTO emp(eid, ename, id) VALUES('121', 'shihuan', :new.id);
END;
INSERT INTO dept VALUES('755', 'GGHJ');
CREATE OR REPLACE TRIGGER update_dept
after UPDATE ON dept
FOR EACH ROW
BEGIN
UPDATE emp SET id = :new.id WHERE id = :old.id;
END update_dept;
UPDATE dept SET id = '999' WHERE id = '01';
CREATE OR REPLACE TRIGGER books_delete
after DELETE ON books
FOR EACH ROW
BEGIN
IF :old.books_id = '0001' THEN
RAISE_APPLICATION_ERROR(-20000, '不允许删除!');
END IF;
END books_delete;
DELETE FROM books WHERE books_id='0001';
【注】在触发器内部是不允许写COMMIT和ROLLBACK的,同样也不支持DBMS_OUT_PUTLINE包代码。
语句级触发器不涉及数据的完整性问题。
CREATE OR REPLACE TRIGGER dml_tabName
AFTER INSERT OR DELETE OR UPDATE ON tabName
BEGIN
IF INSERTING THEN
INSERT INTO mylog VALUES(user, sysdate, 'I');
ELSIF DELETING THEN
INSERT INTO mylog VALUES(user,sysdate, 'D');
ELSE
INSERT INTO mylog VALUES(user, sysdate, 'U');
END IF;
END;
【注】其中user和sysdate是ORACLE的两个系统函数值。
UPDATE tabName SET name='shihuan' WHERE id='11';
DELETE FROM tabName WHERE id='22';
INSERT INTO tabName VALUES('tt', 'gg' ,'yy');
SELECT curr_user, TO_CHAR(curr_date, 'yyyy-mm-dd hh24:mi:ss') FROM tabName;
让id自增的触发器:
CREATE OR REPLACE TRIGGER set_no
BEFORE INSERT ON auto
FOR EACH ROW
DECLARE
sn number(5);
BEGIN
SELECT myseq.nextval INTO sn FROM dual;
:new.a := sn;
END;
【注】BEFORE表示在执行触发器之前做个预处理,sn为number型变量,要特别注意:new.a := sn这一句,这句的含义是先把:new.a赋 个值(即:做个预处理)。
INSERT INTO auto VALUES(32, 'dfg');
INSERT INTO auto VALUES(21, 'rte');
INSERT INTO auto VALUES(45, 'poi');
结果是自增值被插入到数据库中了,而32、21和45这个三个值并没有被插入到数据库中。
替换触发器可以实现向试图中插入数据(替换触发器只能建立在试图上,不能建立在表上):
CREATE OR REPLACE TRIGGER tr_v_e_d
INSTEAD OF INSERT ON v_emp_dept
FOR EACH ROW
BEGIN
INSERT INTO dept VALUES(:new.id, :new.name);
INSERT INTO emp(eid, ename, sex, id) VALUES(:new.eid, :new.ename, :new.sex, :new.id);
END;
如果触发器有问题我们可以通过show errors语句进行查看。
INSERT INTO v_emp_dept VALUES('456', 'test', 'f', '33', 'gjh');