Вы находитесь на странице: 1из 29

DEFINICION DE DISPARADOR O TRIGGER

UN TRIGGER O DISPARADOR ES UN BLOQUE DE CDIGO QUE SE EJECUTA AUTOMTICAMENTE CUANDO OCURRE ALGN EVENTO (COMO INSERCIN, ACTUALIZACIN O BORRADO) SOBRE UNA TABLA ES DECIR CUANDO SE INTENTAN MODIFICAR LOS DATOS DE UNA TABLA ASOCIADA A UN DISPARADOR.

DISPARADOR DE INSERCION DISPARADOR DE BORRADO


A NIVEL DE SENTENCIA Y A NIVEL DE FILA DISPARADOR DE INSERCION A NIVEL DE SENTENCIA create or replace trigger NOMBREDISPARADOR MOMENTO insert On NOMBRETABLA Begin CUERPO DEL TRIGGER End NOMBRE DISPARADOR DISPARADOR DE INSERCION A NIVEL DE FILA
create or replace trigger NOMBREDISPARADOR MOMENTO insert On NOMBRETABLA For each row begin CUERPO DEL TRIGGER End NOMBRE DISPARADOR

DISPARADOR DE BORRADO A NIVEL DE SENTENCIA Y DE FILA

create or replace trigger NOMBREDISPARADOR MOMENTO delete On NOMBRETABLA NIVEL statement o for each row begin CUERPO DEL TRIGGER End NOMBRE DISPARADOR

Ejemplo. SQL> create table productos( id_producto number(6), Nombre_Producto varchar(40), Precio_Producto varchar(30), Cantidad_Producto number(4), constraint pk_productos primary key (id_producto)); Table created. SQL> create table control( user_name varchar(50), fecha date); Table created.

Creamos el disparador
SQL> create trigger ingresar_productos before insert on productos begin insert into control values (user,sysdate); end ingresar_productos; /

Trigger created.

Para establecer el formato de la fecha usamos el siguiente comando


SQL> alter session set NLS_DATE_FORMAT ='DD/MM/YYYY HH24:MI';

Session altered.

Para verificar que nuestro trigger a sido creado usamos lo siguiente


SQL> select trigger_name from user_triggers; TRIGGER_NAME -----------------------------TS_DOS DIS_PAGO INGRESAR_PRODUCTO INGRESAR_PRODUCTOS BUPCUOTA REPCATLOGTRIG DEF$_PROPAGATOR_TRIG 7 rows selected.

Para verificar que nuestro trigger a sido creado ingresamos datos

SQL> insert into productos a values (100,'arroz',10,50);


1 row created.

Para ver si se activo el triggers


SQL> select * from control; USER_NAME FECHA -------------------------------------------------- ---------------SYSTEM 13/11/2012 09:00

LECCION 2 DISPARADOR DE ACTUALIZACION NIVEL FILA NIVEL DE SENTENCIA


Create or replace trigger NOMBREDISPARADOR MOMENTO update on NOMBRETABLA statement begin CUERPO DEL TRIGGER; end NOMBREDISPARADOR;
Create or replace trigger NOMBREDISPARADOR MOMENTO update on NOMBRETABLA for each row begin CUERPO DEL TRIGGER; end NOMBREDISPARADOR;

Para crear un trigger a nivel de fila


SQL> create or replace trigger actualizar_productos 2 before update on productos 3 for each row 4 begin 5 insert into control values(user,sysdate); 6 end actualizar_productos; 7 / Trigger created.

Actualizamos la tabla y le agregamos una cantidad de productos con el 10 % aumentado.


SQL> insert into productos values (90,'azucar',15,29); 1 row created. SQL> insert into productos values (150,'frijol',25,35); 1 row created. SQL> insert into productos values (130,'javon',50,75); 1 row created. SQL> update productos set Cantidad_Producto=Cantidad_Producto+10 where Cantidad_ producto<100; 4 rows updated.

Comprobamos que el disparador se haya disparado las veces indicadas


SQL> select * from control; USER_NAME FECHA -------------------------------------------------- ---------------SYSTEM 13/11/2012 09:28 SYSTEM 13/11/2012 09:28 SYSTEM 13/11/2012 09:28 SYSTEM 13/11/2012 09:28 4 rows selected.

Mostramos la tabla producto para ver si se a agregado esa cantidad


SQL> select * from productos; ID_PRODUCTO 100 90 150 130 NOMBRE_PRODUCTO arroz azcar frijol jabn PRECIO_PRODUCTO 10 15 25 50 CANTIDAD_PRODUCTO 60 39 45 85

Ejemplo a nivel de sentencia


SQL> create or replace trigger actualizar_productos 2 before update 3 on Productos 4 begin 5 insert into control values (user,sysdate); 6 end actualizar_productos; 7 / Trigger created.

Eliminaremos los datos anterior insertados


SQL> delete from control; 8 rows deleted.

Actualizamos y veremos que el disparador se disparo solo una vez


SQL> update productos set Cantidad_Producto=Cantidad_Producto+10 where Cantidad_ producto<100; 4 rows updated. SQL> select * from control; USER_NAME FECHA -------------------------------------------------- ---------------SYSTEM 13/11/2012 09:33

Ahora veremos un trigger que se dispare con una lista de campos


SQL> create or replace trigger actualizar_productos 2 before update of precio_producto on productos 3 begin 4 insert into control values (user,sysdate); 5 end actualizar_productos; 6 / Trigger created.

Ahora veremos un caso sobre precio_producto cuando si se cumple y cuando no se cumple


SQL> update productos set precio_producto=precio_producto+10 where precio_produc to<100; 4 rows updated. SQL> select * from control; USER_NAME FECHA -------------------------------------------------- ---------------SYSTEM 13/11/2012 09:33

Cuando no se cumple la sentencia


SQL> update productos set cantidad_producto=cantidad_producto+10 where precio_pr oducto<100; 4 rows updated. SQL> select * from control; USER_NAME FECHA -------------------------------------------------- ---------------SYSTEM 13/11/2012 09:33

Leccin 3
Disparador de mltiples eventos Disparador (old , new) Disparador de condiciones whem

Instruccin general de un disparador de mltiples eventos


Create or replace trigger NOMBREDISPARADOR MOMENTO of CAMPO EVENTOS on NOMBRETABLA NIVEL begin CUERPODELDISPARADOR end NOMBREDISPARADOR

SQL> create table productos( 2 id_producto number(6), 3 Nombre_Producto varchar(40), 4 Precio_Producto varchar(30), 5 Cantidad_Producto number(4), 6 constraint pk_productos primary key (id_producto));

INICIAMOS CREANDO LAS TABLAS

Table created.
SQL> create table control( 2 user_name varchar(50), 3 fecha date 4 operacion varchar(20)); Table created.

Luego creamos un disparador a nivel de sentencia que se dispare cada vez que se ingrese , actualice y se elimine un registro de la tabla SQL> create or replace trigger cambios_productos 2 before insert or update or delete 3 on productos 4 for each row 5 begin 6 if inserting then 7 insert into control values (user,sysdate,'insercion'); 8 end if; 9 if updating then 10 insert into control values (user,sysdate,'actualizacion'); 11 end if; 12 if deleting then insert into control values (user,sysdate,'borrado'); 13 end if; 14 end cambios_productos; 15 / Trigger created.

Para ver que nuestro trigger se haya creado.


SQL> select trigger_name from user_triggers; TRIGGER_NAME -----------------------------CAMBIOS_PRODUCTOS 1 rows selected.

SQL> insert into productos values (100,'arroz',10,50); 1 row created

SQL> select * from control; USER_NAME FECHA OPERACION -------------------- -------- -------------------SYSTEM 13/11/12 insercion

SQL> delete from productos where id_producto=100; 1 row deleted.

SQL> select * from control;


USER_NAME FECHA OPERACION -------------------- -------- -------------------SYSTEM 13/11/12 insercion SYSTEM 13/11/12 borrado

Ejemplo de disparadores old y new


SQL> create table productos( 2 codigo number(6), 3 nombre varchar(20), 4 cantidad number(5), 5 precio number(8,2)); Table created. SQL> create table control ( 2 usuario varchar(20), 3 fecha date, 4 codigo number (5), 5 precio_anterior number(8,2), 6 precio_nuevo number (8,2)); Table created.

SQL> insert into productos values (10,'arroz',3,20); 1 row created. SQL> insert into productos values (20,'atun',5,30); 1 row created. SQL> insert into productos values (30,'cerillo',1,15); 1 row created.

La sentencia de nuestro trigger quedara de la siguiente manera


SQL> create or replace trigger actualizar_precio_producto 2 before update of precio 3 on productos 4 for each row 5 begin 6 insert into control values (user,sysdate,:new.codigo,:old.precio,:new.preci o); 7 end actualizar_precio_producto; 8 / Trigger created.

Para ver si nuestro trigger se a creado actualizamos los datos


SQL> update productos set precio=100 where codigo=10; 1 row updated. SQL> select * from control; USUARIO FECHA CODIGO PRECIO_ANTERIOR PRECIO_NUEVO -------------------- -------- ---------- --------------- -----------SYSTEM 13/11/12 10 20 100

SQL> update productos set precio=precio+precio*0.1 where codigo=30; 1 row updated. SQL> select * from control; USUARIO FECHA CODIGO PRECIO_ANTERIOR PRECIO_NUEVO -------------------- -------- ---------- --------------- -----------SYSTEM 13/11/12 10 20 100 SYSTEM 13/11/12 30 15 16,5

Todo lo visto anterior mente era sobre system a continuacin lo vamos hacer sobre usuarios determinados crearemos dos usuarios y le estaremos asignando los privilegios correspondientes volveremos a crear las mismas tablas pero sobre un usuario y que el otro usuario le inserte los datos, tambin crearemos el mismo trigger. Lo dicho anteriormente continuacin. lo estaremos mostrando a

SQL> create table mercancia( 2 IdMercancia number(6), 3 NombreMercancia varchar(40), 4 PrecioMercancia varchar(30), 5 CantidadMercancia number(4), 6 constraint pk_mercancia primary key(IdMercancia));

Table created.
SQL> create table administracion( 2 username varchar(50), 3 fecha date); Table created.

EL SIGUIENTE COMANDO MUESTRA LA CREACIN DE LAS TABLAS

ESTO ES EL TRIGGER QUE SE ESTAR EJECUTANDO CUANDO SE INSERTEN DATOS SOBRE MERCANCA.
SQL> create trigger tr_ingresar_mercancia 2 before insert 3 on mercancia 4 begin 5 insert into administracion values(user, sysdate); 6 end tr_ingresar_mercancia; 7 /

Trigger created.

ESTE COMANDO ES PARA ALTERAR LA HORA Y LA FECHA EN LA QUE SE INSERTEN LOS DATOS SOBRE LA TABLA CONTROL.
SQL> alter session set NLS_DATE_FORMAT = 'DD/MM/YYY HH24:MI';

Tabla que muestra los usuarios que insertaron as como tambin la fecha de insercin el comando de alter session es para modificar la fecha a continuacin mostraremos otra pantalla.

Вам также может понравиться