lunes, 30 de mayo de 2011

Create or replace miTrigger
after update on numEmpleado on propiedad

begin
select numOficina into vOldOfiEmpleado
from empleado
where numEmpleado = :old.numEmpleado;

select numOficina into vNewOfiEmpleado
from empleado
where numEmpleado = :new.numEmpleado;

if vNewOfiEmpleado <> vOldOfiEmpleado then

Desarrollar un trigger que mantenga actualizado el numero de propiedades
que administra una oficina.

* Seguir primero que todo los pasos que sale en blackboard

Pasos:
1) select * propiedad

2) ALTER TABLE PROPIEDAD add totPropiedad numeric

3)select e.numoficina, count(p.numpropiedad)
from  propiedad p, empleado e
where p.numempleado = e.numempleado
group by e.numoficina

4) create view mivista as
select e.numoficina, count(p.numpropiedad) as Propiedad
from  propiedad p, empleado e
where p.numempleado = e.numempleado
group by e.numoficina

5)alter table oficina add totpropiedad numeric


6) declare cursor micursor
is
select e.numoficina, count(p.numpropiedad) as Propiedad
from  propiedad p, empleado e
where p.numempleado = e.numempleado
group by e.numoficina

vnumoficina oficina.numoficina%type;
vtotpropiedad oficina.totpropiedad%type;

begin
open micusor;
loop
fetch micursor into vnumoficina, vtotpropiedad
exit when micursor%notfound
 update oficina
 set totpropiedad = vtotpropiedad
 where numoficina = vnumoficina;
end loop;
close micursor;
end;

7) se realiza un update a la tabla oficina para colocar en 0 a los registros nulos.
update oficina
set totpropiedad = 0
where totpropiedad is NULL
desarrollar un triger que mantenga actualizado el numero de propiedades que administra una oficina

lunes, 23 de mayo de 2011

Create or Replace Trigger Transaccion
Before insert on Giro
For each row
DECLARE

Vsaldo cuenta.saldo%type;
Vlimite lineacredito.saldo%type;
Descuento lineacredito.saldo%type;
line lineacredito.saldo%type;

Begin

Select saldo into Vsaldo
From Cuenta
Where IdCuenta= :new.IdCuenta;

Select saldo into Vlimite
From LineaCredito
Where IdCuenta= :new.IdCuenta;




if Vsaldo+Vlimite >= :new.monto then
Descuento := :new.monto - Vsaldo;


Update Cuenta
Set Saldo = Saldo-:new.Monto
where Idcuenta= :new.IdCuenta;

Update LineaCredito
Set Saldo = Saldo - Descuento
where Idcuenta = :new.IdCuenta;

Select IdLinea into line
From LineaCredito
Where IdCuenta= :new.IdCuenta;


insert into UsoLinea values (id_uso.nextval,line,sysdate,Descuento);

Else
dbms_output.put_line('No Alcanza el Saldo Disponible');
End if;
End Transaccion;


CREATE SEQUENCE id_uso
INCREMENT BY 1
START WITH 1



ALTER TABLE algo DROP COLUMN nombre
Create table LineaCredito(
IdLinea number,
IdCuenta number,
Saldo number,
constraint lineaCredito_pk primary key (IdLinea)enable,
CONSTRAINT fk_lineaCredito FOREIGN KEY (IdCuenta)REFERENCES Cuenta(IdCuenta)
)

Create table UsoLinea(
IdUso number,
IdLinea number,
Fecha Date,
Monto number,
constraint usoLinea_pk primary key (IdUso)enable,
CONSTRAINT fk_usoLinea FOREIGN KEY (IdLinea)REFERENCES LineaCredito(IdLinea)
)
create table Cliente(
IdCliente number,
constraint cliente_pk primary key (IdCliente )enable)

create table Cuenta(
IdCuenta number,
IdCliente number,
Saldo number,
constraint Cuenta_pk primary key (IdCuenta)enable,
CONSTRAINT fk_Cuenta FOREIGN KEY (IdCliente)REFERENCES Cliente(IdCliente )
)

Create table Giro(
IdGiro number,
IdCuenta number,
Fecha Date,
Monto number,
constraint Giro_pk primary key (IdGiro )enable,
CONSTRAINT fk_Giro FOREIGN KEY (IdCuenta )REFERENCES Cuenta(IdCuenta ))

jueves, 19 de mayo de 2011

insert into Cuenta values(1,1,1000)
insert into Cliente values(1)
insert into LineaCredito values(1,1,500)
select * from cuenta
select * from lineacredito

Update Cuenta
Set
Saldo = 1000
where Idcuenta= 1;

select trigger_name
from user_triggers;


insert into Giro values(5,1,'01/01/22',2000)

Create or Replace Trigger trTransaccion
Before insert on Giro
For each row
Begin
Update Cuenta
Set
Saldo = Saldo - :new.Monto
where Idcuenta= :new.IdCuenta;
End trTransaccion;

Drop trigger trTransaccion ;


Create or Replace Trigger trMerma
Before insert on Giro
For each row
DECLARE
Vsaldo cuenta.saldo%type;
Vlimite lineacredito.saldo%type;
Descuento lineacredito.saldo%type;
Begin

Select saldo into Vsaldo
From Cuenta
Where IdCuenta= :new.IdCuenta;

Select saldo into Vlimite
From LineaCredito
Where IdCuenta= :new.IdCuenta;


if Vsaldo+Vlimite <= :new.monto then
vSaldo := :new.monto;
Else
dbms_output.put_line('No Alcanza el Saldo Disponible');
End if;
Update Cuenta
Set Saldo = Saldo - :new.Monto
where Idcuenta= :new.IdCuenta;

End trMerma;
Create or Replace Trigger trTransaccion
Before insert on giro
For each row
DECLARE
Vsaldo cuenta.saldo%type;
Vlimite lineaCredito.saldo%type;
Begin
 Select saldo into vLimite
 From lineaCredito
 Where idCuenta = :new.idCuenta;

 if vsaldo+vLimite <= :new.monto then
    vSaldo := :new.monto;
 Else
    dbms_output.put_line('No hay saldo disponible');
 End if;

Update Cuenta
 Set Saldo = Saldo - :new.Monto
 where Idcuenta= :new.IdCuenta;
End trTransaccion;
Create or Replace Trigger trTransaccion
Before insert on Giro
For each row
Begin
 Update Cuenta
 Set
   Saldo = Saldo - :new.Monto
   where Idcuenta= :new.IdCuenta;
End trTransaccion;

select * from cuenta

select * from giro

insert into giro values (2,1,'01/01/11',1)

insert into cuenta values (2,1,200)

lunes, 16 de mayo de 2011

Create table compra (
idCompra numeric,
fechaCompra date,
constraint compra_pk primary key (idCompra)
enable)

create table producto (
idProducto numeric,
nombreProducto varchar(30),
stockActual numeric,
constraint producto_pk primary key (idProducto)
enable)

create table DetalleCompra(
IdCompra numeric ,
IdProducto numeric,
Cantidad numeric,
CONSTRAINT fk_detalle FOREIGN KEY (idCompra)
REFERENCES compra(idCompra),
CONSTRAINT fk_detalle2 FOREIGN KEY (idProducto)
REFERENCES producto(idProducto)
);

lunes, 9 de mayo de 2011

CREATE or replace TRIGGER PersonCheckAge
after delete ON Autor
for each row
begin
delete from Libro
where Libro.idautor =:old.idautor;
end

create table autor(
idautor number )
create table libro(
idlibro number ,
idautor number )
insert into libro values(1,1)

drop table autor
drop table libro
delete from autor where idautor = 1
select * from libro
select * from autor

jueves, 5 de mayo de 2011

CREATE or replace TRIGGER PersonCheckAge
AFTER INSERT OR UPDATE OF age ON Person
FOR EACH ROW
BEGIN IF
(:new.age < 0)
THEN
Raise_application_error(-20000, 'no negative age allowed');
END IF;
END;


insert into person values(-82);

select*
from persona
desc persona
delete from persona

create table persona(
idpersona numeric primary key,
edad numeric
constraint checkedad check (edad >=0));



insert into persona values (incremento_id_cliente.nextval,10)

CREATE SEQUENCE incremento_id_cliente
INCREMENT BY 1
START WITH 100

insert into persona(edad) values (20);
insert into persona values (incrementar.nextval,10);

CREATE SEQUENCE incrementar
INCREMENT BY 1
START WITH 1

CREATE or replace TRIGGER Aumentoo
Before INSERT ON Persona
for each row
BEGIN
insert into persona (idpersona) values (incrementar.nextval);
END;


Petunia mascalo con mayo
create or replace trigger persona
before insert on persona
for each row
begin
select personaseq.nextval into :new.idpersona from dual;
end;

insert into persona (edad) values(20)

select * from persona
¿Cómo crear una secuencia mediante SQL?
Para crear una secuencia en Oracle mediante SQL utilizaremos el comando create sequence con la siguiente sintaxis:
CREATE SEQUENCE nombre_secuencia
INCREMENT BY numero_incremento
START WITH numero_por_el_que_empezara
MAXVALUE valor_maximo | NOMAXVALUE
MINVALUE valor_minimo | NOMINVALUE
CYCLE | NOCYCLE
ORDER | NOORDER
Por ejemplo, si queremos crear una secuencia que empiece en 100 y se incremente de uno en uno utilizaremos la siguiente consulta SQL:
CREATE SEQUENCE incremento_id_cliente
INCREMENT BY 1
START WITH 100
Para utilizar la secuencia, en primer lugar, crearemos una tabla de prueba (para insertar un registro y comprobar que la secuencia anterior funciona correctamente):
create table clientes (
codigo number not null primary key,
nombre varchar2(100) unique not null,
cif varchar2(15) unique,
fechaalta date)
Para utilizar la secuencia creada en una inserción de fila:
insert into clientes values (
incremento_id_cliente.NextVal,
'AjpdSoft',
'11225522F',
sysdate)
Realizamos otra inserción para comprobar que el incremento es de 1:
insert into clientes values (
incremento_id_cliente.NextVal,
'Otro cliente',
'00000G',
sysdate)
Como se puede observar en el ejemplo anterior, para obtener el siguiente valor de la secuencia almacenada se utiliza el comando: nombre_secuencia.NextVal.
Para comprobar que la secuencia ha funcionado en los inserts anteriores hacemos un SELECT a la tabla "clientes":
select * from clientes
El resultado de este SELECT debe ser de dos registro con "codigo" 100 y 101:
CREATE or replace TRIGGER PersonCheckAge
AFTER INSERT OR UPDATE OF age ON Person
FOR EACH ROW
BEGIN
IF (:new.age < 0) THEN
RAISE_APPLICATION_ERROR(-20000, 'no negative age allowed');
END IF;
END;


insert into Person values (53);

create table persona (
idPersona numeric primary key,
edad      numeric,
constraint checkEdad check (edad >=0));

create sequence personaSeq

insert into persona values (personaSeq.nextval,10)

insert into persona values (11,10)

select * from persona

insert into persona values (10)

delete from persona

lunes, 2 de mayo de 2011

create view PropiedadesPorEmpleado as
select nombre, apellido, count (numPropiedad)as TotalPropiedades
from empleado e, propiedad p
where e.numempleado = p.numempleado
group by nombre, apellido
order by count (numPropiedad) DESC, nombre,apellido


select *
from PropiedadesPorEmpleado


Create table T4 (a Integer, b char (10));
Create table T5 (c char(10),d Integer);

create trigger trig1
after insert on T4
referencing new as newRow
for each row
when (newrow.a <= 10)
begin
INSERT INTO T5 VALUES(:newRow.b, :newRow.a);
end trig1;

begin
insert into T4 values(11,'k');

select * from T5


CREATE or replace TRIGGER TopeDeManejoPropiedadEmpleado
BEFORE INSERT OR UPDATE ON PROPIEDAD
FOR EACH ROW
DECLARE
vcontP Integer;
BEGIN
SELECT COUNT(*) INTO vcontP
FROM PROPIEDAD
WHERE numEmpleado= :new.numEmpleado;
IF vcontP = 3 then
Raise_application_error(-20999, 'Empleado '|| :new.numEmpleado|| ' ya administra 3 propiedades');
END IF;
END

begin
insert into PROPIEDAD values('KM14','16 Holhead','Aberdeem','AB7 5SU','Casa','6','650','C046','SL21');
insert into PROPIEDAD values('PG4A' ,'6 Lawrence St','Glasgow','G119QX','Departamento','3','350','C040','SA9');
insert into PROPIEDAD values('PG36','2 Manor Rd','Glasgow','G114QX','Departamento','3','375','C093','SA9');
insert into PROPIEDAD values('PG21','AV. Matta 150','Santiago','G12','Casa','5','600','C087','SG5' );
insert into PROPIEDAD values('PR01','Macul 120 ','Santaigo','G129AX','Departamento','4','450','C093','SA8');
end

DROP TABLE PROPIEDAD
SELECT *
FROM PROPIEDAD
DESC PROPIEDAD
DELETE TABLE PROPIEDAD
Delete From PROPIEDAD


Create or replace procedure InsertarPropiedades
is
begin
insert into PROPIEDAD values ('PR01','Macul 120 ','Santaigo','G129AX','Departamento','4','450','C093','SA8');
Exception
when others then
dbms_output.put_line('Intena asiganr mas de una propiedad');
end

begin
InsertarPropiedades;
end
CREATE or replace TRIGGER TopeDeManejoPropiedadEmpleado
BEFORE INSERT OR UPDATE ON Propiedad
FOR EACH ROW
DECLARE
 vcontP NUMBER;
BEGIN
 SELECT COUNT(*) INTO vcontP
 FROM Propiedad
 WHERE numEmpleado = :new.numEmpleado;
IF vcontP = 100 THEN
Raise_application_error(-2000, 'Empleado '|| :new.numEmpleado|| 'ya administra 100 propiedades');
END IF;
END

Creando triggers

CREATE TRIGGER trig1
AFTER INSERT ON T4
REFERENCING NEW AS newRow
FOR EACH ROW
WHEN (newRow.a <= 10)
BEGIN
INSERT INTO T5 VALUES(:newRow.b, :newRow.a);
END trig1;

SELECT * FROM T5

vista

create view PropiedadesxEmpleado as
select nombre, apellido, count (numPropiedad)as TotalPropiedades
from empleado e, propiedad p
where e.numempleado = p.numempleado
group by nombre, apellido
order by count (numPropiedad) DESC, nombre,apellido

select * from PropiedadesxEmpleado