martes, 6 de septiembre de 2011

Para que el servidor muestre los resultados.

set serveroutput on

Cursor que liste de all_tables y de all_tab_columns, nombre de tabla y atributo

declare
cursor CrListaAtributos (pTabla varchar2) is
    select COLUMN_NAME
    from all_tab_columns
    where TABLE_NAME = pTabla ;
    cursor CrListatablas is
    select distinct tablas.table_name
    from all_tables tablas
    where table_name not like '%$%'
    and owner not like '%SYS%';
  
    vNomTabla all_tables.table_name%type;
    vAtributoTabla all_tab_columns.table_name%type;
  

begin
    open CrListatablas;
    loop
      
    fetch CrListatablas into vNomTabla;
    exit when CrListatablas %notfound;
        dbms_output.put_line('--------------------------------');
    dbms_output.put_line(vNomTabla);
        dbms_output.put_line('--------------------------------');
    open CrListaAtributos(vNomTabla);
  
    loop
    fetch CrListaAtributos into vAtributoTabla;
    exit when CrListaAtributos%notfound;
    dbms_output.put_line(vAtributoTabla);
    end loop;
    close CrListaAtributos;
    end loop;
    close CrListatablas;
end;

Servidor Duoc

http://oracle:5560/isqlplus/

lunes, 5 de septiembre de 2011

contar cuantos empleados hay por cada departamento :
Creamos un atributo en la tabla departments :
ALTER table DEPARTMENTS add TotEmplexDepartamento number(100)
Ahora procedo a realizar el cursor :
Declare cursor
miCursor is
select e.department_id, count(p.employee_id) as Empleados
from Departments e, Employees p
where p.department_id = e.department_id
group by p.department_id;
vnumdepartamento employees.employee_id%type;
vtotempleados employees.employee_id%type;
begin
open micursor;
loop
fetch micursor into vnumdepartamento,vtotempleados;
exit when micursor%notfound;
update DEPARTMENTS set TotEmplexDepartamento= vtotempleados 
where department_id= vnumdepartamento
end loop;
close micursor;
End;

martes, 30 de agosto de 2011

Cursor

--Cursor que permita determinar los empleados cuyo cargo sea finance manager o programmer, que tienen una renta menor o igual al promedio entre el salario minimo y maximo definido en la tabla jobs--
--Para los empleados que tiene menos del promedio estudiar aumento y para los que tengan mas estudiar carga de trabajo--
-- Generando un registro en la tabla , estudio_sueldo, donde se graben el id_empleado , nombre , apellido , renta , y diferencia con promedio--



Create table estudio_sueldo(
EMPLOYEE_ID number (6),
FIRST_NAME varchar2 (20),
LAST_NAME varchar2 (25),
SALARY number (8,2),
PROMEDIO number (8,2),
MESSAGE varchar2 (30))


Incompleto

Declare
cursor miCursor is
 Select first_name , last_name, e.job_id, employee_id, salary
 From Employees e, Jobs j
 Where e.job_id = j.job_id
 and job_title = 'Finance Manager'
 or job_title = 'Programmer';
vNombre employees.first_name%type;
vApellido employees.last_name%type;
vJobid employees.job_id%type;
vEmpleadoid employees.employee_id%type;
vSalario employees.salary%type;
vSueldoMin employees.salary%type;
vSueldoMax employees.salary%type;
vPromedio number (8,2);
Begin
open miCursor;
loop
fetch miCursor into vNombre,vApellido,vJobid,vEmpleadoid,vSalario;
exit when miCursor%notfound;
dbms_output.put_line(vNombre ||' '||vApellido||' '||vJobId||' '||vEmpleadoId||' '||vSalario);
select min_salary , max_salary into vSueldoMin, vSueldoMax
from jobs
where vJobId = job_id
vPromedio = (vSueldoMin + vSueldoMax)/2;
if vSueldo >= vPromedio
then vMessage := 'evaluar carga de trabajo'
else
vMessage := 'Estudiar aumento de sueldo';
end if;
--Falta calcular la diferencia ente los sueldos y promedios--
--Realizar enunciado--
insert into estudio_sueldo values (vEmpleadoid,vNombre,vApellido,vSalario, vPromedio)
end loop;
close miCursor;
End;

Consultas

Select first_name , last_name, e.job_id
From Employees e, Jobs j
Where e.job_id = j.job_id
and job_title = 'Finance Manager'


--(Tiene que estar igual el campo a buscar que en la tabla)--
-- Si no se realiza el lower o upper ---



Select first_name , last_name, e.job_id
From Employees e, Jobs j
Where e.job_id = j.job_id
and lower (job_title) = 'finance manager'

-- Listar todos los empleados que tienen los cargos finance manager , programmer --

Select first_name , last_name, e.job_id
From Employees e, Jobs j
Where e.job_id = j.job_id
and job_title = 'Finance Manager'
or job_title = 'Programmer'

martes, 23 de agosto de 2011

Cursor.-

select department_id as "Departamento",
count(*) as "Total Empleado"
From employees
group by department_id


select DEPARTMENT_NAME as "departamento",
count(*) as "totalEmpleados"
from DEPARTMENTS d, EMPLOYEES e
Where e.DEPARTMENT_ID = d.DEPARTMENT_ID
Group by DEPARTMENT_NAME   

Seleccionar el nombre de los departamentos donde trabaja el empleado.

select DEPARTMENT_NAME ,count(EMPLOYEE_ID)
from DEPARTMENTS d, EMPLOYEES e
Where e.DEPARTMENT_ID = d.DEPARTMENT_ID
Group by DEPARTMENT_NAME
Order by DEPARTMENT_NAME
---------------------------------------------
Cursor

Declare
cursor miCursor is
select department_id ,
count(*)
From employees
group by department_id
Order by department_id;
   
vDepartamento employeeS.employee_id%type;
vTotEmpleado integer;

Begin
open miCursor;
dbms_output.put_line('Departamento TotEmpleado');
loop
fetch miCursor into vDepartamento, vTotEmpleado;
exit when miCursor%notfound;
dbms_output.put_line(vDepartamento || '                ' || vTotEmpleado);
end loop;
close miCursor;
End;



----------------------------------------------
Saber cual es el nombre de un codigo de un depto.


Declare
vNumeroDepto integer := 10;
vNombreDepto char(50);
begin
Select DEPARTMENT_NAME into vNombreDepto
from departments
where department_id = vNumeroDepto;
dbms_output.put_line('El codigo del depto es : ' || vNumeroDepto);
dbms_output.put_line('El codigo del depto es : ' || vNombreDepto);
end;

jueves, 30 de junio de 2011

  1. http://pdb002.blogspot.com/search?updated-max=2011-05-02T16%3A21%3A00-07%3A00&max-results=7
create or replace package pkgMipaquete is
function suma (p1 number, p2 number) return number;
function resta (p1 number, p2 number) return number;
function multiplica(p1 number, p2 number) return number;
function divide(p1 number, p2 number) return number;
end pkgMipaquete;
create or replace package BODY pkgMipaquete is
procedure imprime(pvalor number) is
BEGIN
dbms_output.put_line('Resultado : ' || pvalor);
end;
function suma(p1 number, p2 number) return number is
begin
imprime(p1+p2);
return(p1+p2);
end suma;
function resta(p1 number, p2 number) return number is
begin
imprime(p1-p2);
return(p1-p2);
end resta;
function multiplica(p1 number, p2 number) return number is
begin
imprime(p1*p2);
return(p1*p2);
end multiplica;
function divide(p1 number, p2 number) return number is
begin
imprime(p1/p2);
return(p1/p2);
EXCEPTION
when zero_divide then
dbms_output.put_line ('Cuack : Division por cero');
return 0;
end divide;
end pkgMipaquete;
declare
r number(10);
begin
r:= pkgMipaquete.suma(2,3);
end

jueves, 16 de junio de 2011

Corregir

1.       Realizar una función que reciba una  cadena ej:  'ARCA' y la muestre por consola repetida n veces Ej: 7 veces.


CREATE OR REPLACE function RepiteCadena(pstr1 varchar2,pn number)
return varchar2 as
 str2 varchar(100) = null;
 i numeric = 1;
 begin
 loop
   str2 = concat(str2,pstr1);
   i = i + 1;
   exit when i >= pn;
 end loop;
 return str2;
 end;
2. Crear un procedimiento con un cursor que actualice el atributo TotEmpleado

Declare
cursor miCursor
is

select e.numoficina, count(e.numempleado) as Empleados
from oficina p, empleado e
where p.numoficina = e.numoficina
group by e.numoficina;

vnumoficina oficina.numoficina%type;
vtotempleado oficina.numoficina%type;

begin
open micursor;
loop
fetch micursor into vnumoficina, vtotempleado;
exit when micursor%notfound;
update oficina
set totempleado = vtotempleado
where numoficina = vnumoficina;
end loop;
close micursor;
End;


select * from oficina

lunes, 13 de junio de 2011

Desarrollar 4 funciones ,
Desarrollar 4 trigger,
Desarrolar 4 cursores

Enunciado , implementación y el llamado.
http://www.scribd.com/doc/49946651/27/Funciones-en-PL-SQL

2. Crear otra función que al ingresar un número entero......entregue por consola el numero elevado al cubo.



CREATE OR REPLACE FUNCTION elevarAlCubo(n1 Numeric)
RETURN numeric
is
BEGIN
return power(n1,2);
END;

SELECT elevarAlCubo(2) from dual;
1. Crear una función que reciba 2 números y los sume...y el resultado lo muestre por la consola.


CREATE OR REPLACE FUNCTION sumar(n1 Numeric,n2 numeric)
RETURN numeric
is
BEGIN
return n1+n2;
END;


SELECT sumar(4,2) from dual;

jueves, 2 de junio de 2011

PARA QUE SIRVE LOS CURSORES,

CUANDO SE HACE UNA CONSULTA Y ENTREGA UNA CANTIDAD DE VALORES ,
LOS CURSORES SIRVEN PARA HACER UN RECORRIDO DE LA TABLA.

NO DEJAR REGISTRO DE ACTUALIZACIONES

CREATE or replace TRIGGER trLogRenta
after update of salario on empleado
for each row
BEGIN
if :new.salario <> :old.salario then

 insert into RENTALOG VALUES (SEQRENTALOG.nextval,
 user,
 sysdate,
 :old.salario,
 :new.salario,
 :old.numempleado);
end if;
END;

REGISTRO 2 , con la misma renta

REGISTRO

CAMBIAR DE RENTA A UN 20% +

UPDATE EMPLEADO
SET SALARIO = SALARIO * 1.2
WHERE NUMEMPLEADO = 'SL21'

SENTENCIAS

INSERT (..)
:NEW
DELETE (..)
:OLD

VERIFICAR ERROR EN EL TRIGGER

SHOW ERR TRIGGER trLogRenta

INSTRUCCION

crear trigger que cada vez que modifique el sueldo de un empleado deje registro.

crear trigger que cada vez que modifique el sueldo de un empleado deje registro.

create table RENTALOG (
IDRENTALOG NUMERIC primery key,
USUARIO VARCHAR(20),
FECHA DATE,
SUELDOANTIGUO FLOAT,
SUELDONUEVO FLOAT,
NUMEMPLEADO VARCHAR(20)
);

CREATE SEQUENCE SEQRENTALOG
INCREMENT BY 2
START WITH 10

CREATE or replace TRIGGER trLogRenta
after update of salario on empleado
for each row
BEGIN
insert into RENTALOG VALUES (SEQRENTALOG.nextval,
user,
sysdate,
:old.salario,
:new.salario,
:old.numempleado);
END;
Declare
cursor miCursor
is
select e.numoficina, count(p.numpropiedad) as Propiedades
from propiedad p, empleado e
where p.numempleado = e.numempleado
group by e.numoficina;

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

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

Create or replace trigger miTrigger
after  delete or insert or update of numempleado on propiedad
for each row
declare
vOldOfiEmpleado char(4);
vNewOfiEmpleado char(4);
begin
  if updating then
 select numoficina into vOldOfiEmpleado
 from empleado
 where numempleado = :old.numempleado;
 select numoficina into vNewOfiEmpleado
 from empleado
 where numempleado = :new.numempleado;
 if vOldOfiEmpleado <> vNewOfiEmpleado then
update oficina
set totPropiedad = totPropiedad - 1
where numOficina = vOldOfiEmpleado;

update oficina
set totPropiedad = totPropiedad + 1
where numOficina = vNewofiEmpleado;
 end if;
 else
    if deleting then
 select numoficina into vOldOfiEmpleado
      from empleado
      where numempleado = :old.numempleado;

 update oficina
 set totPropiedad = totPropiedad - 1
 where numOficina = vOldOfiEmpleado;
else
select numoficina into vNewOfiEmpleado
        from empleado
        where numempleado = :new.numempleado;
update oficina
   set totPropiedad = totPropiedad + 1
   where numOficina = vNewofiEmpleado;
end if;
end if;
end;


Chequeamos los

select e.numempleado, p.numpropiedad
from empleado e, propiedad p
where numoficina = 'B005'
and e.numempleado = p.numempleado

Buscamos algun empleado que no tenga propiedades

Vamos a cambiar la asignacion de la propiedad "PG16" que la tiene el
empleado "SL22" de la oficina "B005" con 5 propiedades y la asignamos al empleado "SG37" de la oficina "B006" que no
tiene propiedades.

Hacemos el siguiente update

update propiedad
set numempleado = 'SG37'
where numpropiedad = 'PG16';

Eliminando la propiedad "PL94" de la oficina "B005" que le quedan 4 propiedades

delete from propiedad
where numpropiedad = 'PL94'

Ahora insertamos una nueva propiedad al empleado "SG37" de la Oficina "B006"

insert into PROPIEDAD values('P007','Nueva','Aberdeem','AB7 5SU','Casa','6','650','C046','SG37');

Finalmente la Oficina "B006" deberia quedar con DOS (2) Propiedades

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

jueves, 28 de abril de 2011

Create or replace procedure CrearTablas
is
begin
if VerificaTabla('PROPIEDAD')then
execute immediate 'Drop table PROPIEDAD';
end if;
if VerificaTabla('EMPLEADO')then
execute immediate 'Drop table EMPLEADO';
end if;
if VerificaTabla('OFICINA')then
execute immediate 'Drop table OFICINA';
end if;

execute immediate 'Create table OFICINA(
idOficina integer not null,
direccion varchar2(45),
comuna varchar2(25),
ciudad varchar2(35),
codPostal varchar2(10),
constraint PK_OFICINA primary key (idOficina));
)';
execute immediate 'Create table EMPLEADO(
IdEmpleado int not null,
nombre varchar2(30) not null,
apellido varchar2(45)not null,
cargo varchar(35) not null,
sexo char(1)not null,
fechaNacimiento date not null,
salario int not null,
idOficina int not null,
CONSTRAINT ID_PK PRIMARY KEY (IdEmpleado),
CONSTRAINT NN_FK foreign key (IdOficina) references Oficina (IdOficina)
)';
execute immediate 'Create table Propiedad(
IdPropiedad int not null,
direccion varchar2(45) not null,
comuna varchar2(25)not null,
ciudad varchar(35) not null,
codigoPostal varchar(10) not null,
tipoVivienda int not null,
numeroHabitaciones int not null,
rentaMensual Float not null,
IdEmpleado int not null,
CONSTRAINT IDD_PK PRIMARY KEY (IdPropiedad),
CONSTRAINT NM_FK foreign key (IdEmpleado) references Empleado (IdEmpleado)
)';
end;

DESC OFICINA

begin
CrearTablas;
end

begin
if VerificaTabla('employees')= TRUE then
dbms_output.put_line('La tabla existe');
else
dbms_output.put_line('La tabla no existe');
end if;
end

Create or Replace procedure miCursor(pOficina integer)
as
cursor ListaPropiedadesCursor(pcOficina integer)
select nombre, apellido, count(idPropiedad)
from Empleadoe, Propiedad p
where e.idOficina = pcOficina
and e.idEmpleado=p.idEmpleado
group by nombre,apellido;

vnombre Empleado.nombre%type;
vapellido Empleado.nombre%type;
vPropXEmpleado integer;
vTotalxOficina integer;

begin
select Count (idPropiedad) into vTotalxOficina
from PROPIEDAD
where idOficina = pOficina;
1) Cree la función VerificaTabla, que reciba como parámetro un nombre de tabla, y retorne TRUE si la tabla existe o FALSE si la tabla no existe. (TRUE y FALSE son booleanos)


Create or replace function VerificaTabla(pNombre Varchar2)
return boolean
is
vTabla user_tables.table_name%type;
begin
selecT table_name into vTabla
from user_tables
where lower(table_name) = lower(pNombre);
return TRUE;
Exception
when NO_DATA_FOUND then
return FALSE;
end;

begin
if VerificaTabla('employees')= TRUE then
dbms_output.put_line('La tabla existe');
else
dbms_output.put_line('La tabla no existe');
end if;
end

lunes, 18 de abril de 2011

//Creo la tabla oficina
create table OFICINA (
NUMOFICINA CHAR(4) not null,
CALLE CHAR(30),
CIUDAD CHAR(25),
CODIGOPOSTAL CHAR(10),
constraint PK_OFICINA primary key (NUMOFICINA)
);
----------------------------------------------------------------------------------------------

//Diseñar un PA para Modificar la tabla oficina agregándole la columna Direccion.

create or Replace PROCEDURE agregarDireccion
as
BEGIN
execute immediate 'alter table Oficina
  add Direccion varchar2(40)';
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('Error en agregar atributo');
END;

-----------------------------------------------------------------------------------------------
//Compruebo que en mi tabla "Oficina" este el atributo "Direccion" agregado.
DESCRIBE OFICINA

-----------------------------------------------------------------------------------------------

create or Replace PROCEDURE agregarDireccion
as
BEGIN
execute immediate 'alter table Oficina
  add Direccion varchar2(40)';
EXCEPTION
when NO_DATA_FOUND then
dbms_output.put_line('se gatilla NO_DATA_FOUND');
WHEN OTHERS THEN
dbms_output.put_line('se gatilla OTHERS supongo porque La tabla OFICINA no existe');
END;


bibliografia de errores que se le pueden agregar:
http://www.devjoker.com/contenidos/Tutorial-PLSQL/48/Excepciones-en-PLSQL.aspx
-----------------------------------------------------------------------------------------------
//Escriba un programa que gatille una excepción al tratar de eliminar un registro inexistente.
create or replace PRODECURE eliminarRegistro (pnumOficina oficina.numOficina%type)
is
    vnumoficina oficina.numoficina%type;
begin
    select numoficina into vnumoficina
    from oficina
    where numoficina = pnumOficina;

    delete from oficina
    when numOficina = pnumOficina;
exception
    when NO_DATA_FOUND then
    dbms_output.put_line('Registro :' || pnumoficina || ' No existe para eliminarlo);
End;

-----------------------------------------------------------------------------------------------
//Crear una función de calcule el total de empleados por Oficina.
create or replace FUNCTION CuentaEmpleados (pnumOficina oficina.numOficina%type)
return interger;
as
    vtotEmpleados interger :=0;
    vnumoficina oficina.numoficina%type;
begin
    select numoficina into vtotEmpleados
    from oficina
    where numoficina = pnumOficina;

    select count(numoficina) int vtotEmpleados
    from empleados
    where numoficina = pnumOficina;
    return vtotEmpleados;
exception
    when NO_DATA_FOUND then
    dbms_output.put_line('Oficina :' || pnumoficina || ' No existe');
    return 0;
End;

jueves, 14 de abril de 2011

create or replace procedure IngresarVisita(Pnumero Number,Pdescripcion Varchar2)
is
begin
INSERT INTO Visita
(Numvisita,Descripcion)
values
(Pnumero,Pdescripcion );
dbms_output.put_line('Visita Ingresada Numero: ' ||Pnumero ||' Descripcion :' ||Pdescripcion );
end;



begin
IngresarVisita(4,'mamamam');
end;
create or replace procedure VerCliente(Pnumcliente Number)
is
Vnombre employees.first_name%type;
Vapellido employees.last_name%type;
begin
select first_name,last_name into Vnombre,Vapellido
from employees
where employee_id = Pnumcliente ;
dbms_output.put_line('El cod ingresado es : '||Pnumcliente ||' Nombre: ' ||Vnombre ||' Apellido: '||Vapellido );
end;

begin
VerCliente(101) ;
end;

lunes, 11 de abril de 2011


1.-Crear una función SumaDos (n1, n2) que reciba 2 numeros y retorne la suma de ellos.
CREATE OR REPLACE FUNCTION sumaDos (n1 Numeric, n2 Numeric)
RETURN numeric
is
BEGIN
return (n1 + n2);
END;
2.-Crear la Función Potencia (n, p) que reciba un numero y retorne el numero elevado a la potencia p
CREATE OR REPLACE FUNCTION Potencia100 (n Numeric,p Numeric)
RETURN numeric
is
BEGIN
loop
return power(n,p);
end loop;
END;

create or replace function Potencia69(n Numeric, p Numeric)
return numeric;
is
resultado numeric := 1;
begin
for i in 1..p
loop
resultado := resultado * p;
 end loop;
return resultado;
end
3.-Escribir la funcion MayorDeTres (n1, n2, n3) que retorne el mayor de los tres elementos ingresados
CREATE OR REPLACE FUNCTION mayorDeTres (n1 numeric, n2 numeric, n3 numeric)
RETURN numeric
is
BEGIN
RETURN (GREATEST(n1,n2,n3));
END;
4.-Diseñar una función  Invertir3 (n) que reciba un numero de tres digitos y retorne el numero invertido. Ej: 123 retorna 321

5.-Implementar una funcion invertirN(n) que reciba un numero de N digitos y retorne el numero invertido

6.-Escriba la función BuscaString (Srt1, Str2) y retorna Verdadero o falso segun si el Str2 se encuentra en Str1

jueves, 7 de abril de 2011

CREATE OR REPLACE FUNCTION darteVuelta (pN Numeric)
RETURN numeric
is
BEGIN
return (mod(pN,10)*10+trunc(pN/10));
END;

SELECT darteVuelta(12) from dual;


SELECCIONA UN DATYO TIPO NUMERICO Y LO DA VUELTA
CREATE OR REPLACE FUNCTION darteVuelta (pN Numeric)
RETURN numeric
is
BEGIN
return reverse(pN);
END;

SELECT reverse('123') from dual;
CREATE OR REPLACE FUNCTION CalculaParImpar (pN Numeric)
RETURN varchar2
is
BEGIN
if MOD(pN,2) = 0 Then
  return 'par';
else
  return 'impar';
end if;
END;

SELECT CalculaParImpar (3) from dual;

CALCULA PAR E IMPAR

lunes, 28 de marzo de 2011

Actualizar y Contar

declare
a empleado.cantidad%TYPE;
b empleado.numempleado%TYPE;

cursor Actualizar is select numempleado,count(*)
from propiedad
group by numempleado;

begin
open Actualizar ;
loop
fetch Actualizar into b,a;
update empleado set cantidad = a where numempleado = b;
dbms_output.put_line('ACualizado :'||b ||a);
exit when Actualizar%NOTFOUND;
end loop;
CLOSE Actualizar;
end;

jueves, 24 de marzo de 2011

Agregue un atributo a la tabla EMPLOYEES, denominado TipoId, que va a contener un string.

Desarrolle un cursor que permita completar dicho atributo de acuerdo al siguiente criterio:

SI employee_id es Par

Entonces

TipoId = ‘PAR’

Si-no

TipoId = ‘IMPAR’

---------------------------------------------------------------------------------------
ALTER TABLE employees
MODIFY TipoId Varchar(10);



declare
vEmployee_id employees.employee_id%TYPE;
vTipo employees.first_name%TYPE;



cursor parImparCursor is
select employee_id
from employees for update;



begin
open parImparCursor;
loop
fetch parImparCursor into vEmployee_id;
IF MOD(vEmployee_id,2)=0 THEN
update employees set idtipo ='par' where MOD(Employee_id,2)=0 ;
dbms_output.put_line(vEmployee_id||' PAR ');
ELSE
dbms_output.put_line(vEmployee_id||' IMPAR ');
update employees set idtipo = 'impar';
END IF;
exit when parImparCursor%NOTFOUND;
end loop;
CLOSE parImparCursor;
end;
---------------------------------------------------------------------------------------