Sei sulla pagina 1di 2

Base de datos.

Iniciar Oracle
su oracle;
v sqlplus jardineria/jardineria {/ as
sysdba}
Insert+select
Insert into BackupVehiculos select * from
vehculos;
(Deben tener las mismas columnas)
Puedes copiar la estructura vacia: CREATE
TABLE BackupVehiculos like Vehiculos;
Podemos crear la estructura y los registros a la
vez:
CREATE TABLE BackupVehiculos Select * from
Vehiculos;
Update y delete con subconsultas
DELETE FROM empleados where
CodigoEmpleado Not in (select
CodigoEmpleadoRepVentas From
Clientes) AND Puesto=Representante
Ventas;
Transacciones
Iniciar transacciones.
-Mysql
Begin Work;
-Oracle
Set Autocommit off;
Terminar la transaccin (MYSQL y
Oracle)
Commit work; #acepta los cambios
Rollback work; #cancela los cambios

Programacin (partes de un programa)


SET SERVEROUTPUT ON -- permite escribir
DECLARE -- opcional, declaracin de
variables
BEGIN --sentencias a ejecutar
EXCEPTION -- opcional, chequeo de
errores y acciones a realizar en ese caso
END;
/

Ejemplo de declare
DECLARE
mesInicio Char(2):= 6;
mesFin Char(2):= 10;
mesesTranscurridos NUMBER;

Llamar a un procedimiento desde linea de comandos


Call o exec NOMBREPROCEDIMIENTO(VALORES);

Procedimientos y funciones (se llaman en Oracle con @NOMBRE.sql)


Procedimiento
create or replace procedure EstadoCliente( Cod IN Clientes.CodigoCliente%type)
as

Funcion (devuelve valor al termino de la ejecucion)


Create or replace function ffactorial (n in number) return number
Is

Operadores
** potencia
|| Concatenacion
MOD(N,I) Modulo

Exception
Exception
when no_data_found then
dbms_output.put_line('NO EXISTE CLIENTE ');
when too_many_rows then
dbms_output.put_line('Error, consulta devuelve muchas filas');
when others then
dbms_output.put_line('ERROR CRITICO!');
end;
/
Exception va justo antes del end;
Ejemplo de function (Creacion de la funcion)
Create or replace function ffactorial (n in number) return number
is
fact number:=1;
begin
for i in 1 .. n loop
fact:=fact*i;
end loop;
return fact;
end;
/
Asi creamos la funcin para un numero factorial
Declaracin de Cursor
Sintaxis:
CURSOR nombre_cursor IS Sentencia select ; /* sin INTO */
Ejemplo:
DECLARE
v_empno emp.empno%TYPE;
v_ename emp.empno%TYPE;
CURSOR emp_cursor IS SELECT empno, ename FROM emp WHERE deptno = 30

Variables lista de
parametros en
procedimientos
IN parametro de
entrada
OUT parametro de
salida
IN OUT parmetro de
entrada y salida

If..then
If calificacin >= 0 then
Dbms_output.put_line(Suspenso);
Elsif calificacion >=5
Dbms_output.put_line(Aprobado);
Else
Dbms_output.put_line(Bien);
End if;

Case-when
calificacin:= 6
case
when calificiacion < 5 then
Dbms_output.put_line(Suspenso);
When calificacion > 5 then
Dbms_output.put_line(Aprobado);
End case;

Loop - exit
Contador:=1;
Loop
Exit when contador > 99;
Contador := contador + 1;
End loop;

Whileloop-end loop
Contador:=1;
Loop
while contador < 99;
Contador := contador + 1;
End loop;

For . . in .. loop-end loop


For contador in 1 . . 100 loop
Dbms_output.put_line(contador)
End loop;
La variable del for (contador) no
deben ser definidas en el DECLARE
En lugar de in se puede poner in
reverse para usar el bucle de mayor a
menor
Uso de la funcin en un .sql
set serveroutput on
declare
combina number;
begin
combina:=(ffactorial(49)/(ffactorial(49-6)*ffactorial(6)));
dbms_output.put_line(combina);
end;
/

Ejemplo de cursor
set serveroutput on
declare
--Declaracion de variables y cursores
cursor v_cli is select * from clientes;
begin
for regcli in v_cli loop
dbms_output.put_line(regcli.CodigoCliente||' '||regcli.NombreCliente||'
'||regcli.pais);
end loop;
end;
/

CRITICO!!!!!!!!!!!!');
Otro
ejemplo de cursor con while y fetch
setend;
serveroutput on
/
declare
--Declaracion de variables y cursores
regcli clientes%rowtype; --rowtype hace que la variable coja todas los registros de una tabla
cursor v_cli is select * from Clientes;
begin
-- abrimos el cursor
open v_cli;
fetch v_cli into regcli;
--%found hace que busque en el loop hasta que v_cli sea nulo
while v_cli%found loop
--procesa informacion
dbms_output.put_line(regcli.CodigoCliente||' '||regcli.NombreCliente||'
'||regcli.pais); --para nombrarlo se hace con NOMBREVARIABLE.NOMBRECAMPO
--lee de nuevo
fetch v_cli into regcli;
end loop;
close v_cli;
end;
/

Ejemplo de procedimiento (hecho en clase)


set serveroutput on
create or replace procedure EstadoCliente( Cod IN Clientes.CodigoCliente%type)
as
regcli Clientes%rowtype;
TotalFacturado NUMBER;
TotalPagado NUMBER;
TotalDeuda NUMBER;
begin
select * into RegCli from Clientes where CodigoCliente=Cod;
dbms_output.put_line('Codigo Cliente: '||regcli.CodigoCliente);
dbms_output.put_line('Codigo Cliente: '||regcli.NombreCliente);
select sum(PrecioUnidad*Cantidad) into TotalFacturado from DetallePedidos natural join Pedidos
where CodigoCliente=Cod;
dbms_output.put_line('Total facturado al cliente: '||TotalFacturado);
select sum(Cantidad) into TotalPagado from Pagos where CodigoCliente=Cod;
dbms_output.put_line('El cliente ha pagado: '||TotalPagado);
if TotalFacturado>TotalPagado then
TotalDeuda:=TotalFacturado-TotalPagado;
dbms_output.put_line('El cliente debe: '||TotalDeuda);
else
dbms_output.put_line('El cliente no debe nada');
end if;
exception
when no_data_found then
dbms_output.put_line('NO EXISTE CLIENTE CON ESE CODIGO');
when too_many_rows then
dbms_output.put_line('Error, consulta devuelve muchas filas');
when others then
dbms_output.put_line(' ERROR CRITICO!!');
end;
/

create or replace procedure aumentacredito is


totalpagado number;
totalfacturado number;
cursor cli is select codigocliente,limitecredito from clientes;
begin
for regcli in cli loop
select sum(cantidad) into totalpagado from pagos
where codigocliente=regcli.codigocliente;
select sum(preciounidad*cantidad) into
totalfacturado from detallepedidos natural join pedidos
where codigocliente=regcli.codigocliente;
if nvl(totalfacturado,0)>nvl(totalpagado,0) then

Ejemplo de procedimiento (hecho en clase)


set serveroutput on
create or replace procedure AsignaJefe(trabajador in
Empleados.CodigoEmpleado%type,jefe in
Empleados.CodigoEmpleado%type)
as
jefe_no_valido exception;
begin
if trabajador=jefe then
raise jefe_no_valido;
end if;
update Empleados set CodigoJefe=jefe where
CodigoEmpleado=trabajador;
exception
when jefe_no_valido then
dbms_output.put_line('Un empleado no
puede ser su propio jefe');
when no_data_found then
dbms_output.put_line('No se encuentran
esos datos');
when too_many_rows then
dbms_output.put_line('Demasiadas lineas
devueltas');
when others then
dbms_output.put_line('ERROR
INESPERADO');
end;
/

Ejemplo de funcion
create or replace function porcentaje(a in number,b in number)
return number
is
begin
return ((a*b/100)+a);
end;
/

set serveroutput on
declare
resultado number;
begin
resultado:=porcentaje(100,20);
dbms_output.put_line(resultado);
end;
/

Continua
dbms_output.put_line(regcli.codigocliente||' Total
Facturado: '||totalfacturado||' Total Pagado:
'||totalpagado);
update clientes set
limitecredito=porcentaje(limitecredito,20) where
codigocliente=regcli.codigocliente;
end if;
end loop;
end;
/

Potrebbero piacerti anche