Bienvenidos a un nuevo curso. Ahora estoy en el ciclo de grado superior: Desarrollo de aplicaciones multiplataforma. Y voy a ser parte del experimento de la formación dual. Estaré haciendo practicas durante un año, y a la vez finalizando la formación.

Deseadme suerte.

Mostrando entradas con la etiqueta TRIGGER. Mostrar todas las entradas
Mostrando entradas con la etiqueta TRIGGER. Mostrar todas las entradas

martes, 24 de mayo de 2016

miércoles, 18 de mayo de 2016

repaso 3

0

Puedes acceder  a los ejercicios aquí.



1.-


Una manera más eficiente:

delimiter $$
drop trigger if exists ej1 $$
create trigger ej1
before insert on empleados
for each row
begin
if (select count(cojefe) 
from  empleados 
where cojefe = new.cojefe) = 5
then
SIGNAL SQLSTATE '45000'
      SET MESSAGE_TEXT = 'Sobrepasa los 5';
end if ;

end $$

delimiter ;

2.-



3.-




martes, 10 de mayo de 2016

Examen

0

Puedes acceder a la teoría necesaria para hacer los ejercicios,  a los ejercicios y las bases de datos necesarias aquí, aquí y aquí.

Pregunta 1 

/*mi versión*/
delimiter $$
drop procedure if exists pregunta1 $$
create procedure pregunta1(e_cod_articulo char(4), e_cantidad int, out s_error_num int, out s_error_text varchar(200))
begin
/* declaracion de variables*/
declare v_articulo int;
declare v_existencias int;
/*bloqueación de la fila implicada*/
declare articulos_cursor cursor for
select existencias
from articulos
where cod_articulo=e_cod_articulo
for update;
/* control de errores 1 */
declare exit handler for sqlexception
begin
set s_error_num=0;
set s_error_text='ocurrio un error';
        rollback;
end;
/* valor de las variables */
select count(*)
into v_articulo
from articulos
where cod_articulo=e_cod_articulo;
/*control de errores 2*/
if v_articulo <> 1 then
set s_error_num=-1;
set s_error_text='El articulo no existe';
else
/*transacción*/
start transaction;
open articulos_cursor;
fetch articulos_cursor into v_existencias;
if (v_existencias-e_cantidad)<0 then
set s_error_num=-2;
set s_error_text='La cantidad solicitada es mayor que las existencias';
else
set s_error_num=1;
update articulos set existencias=v_existencias-e_cantidad where                                           cod_articulo=e_cod_articulo;
if s_error_num=1 then
set s_error_text='Actualización realiza con exito';
commit;
end if;
close articulos_cursor;
end if;
end if;
end $$
delimiter ;

/* respuesta profesor */
delimiter $$
drop procedure if exists pregunta1 $$
create procedure pregunta1(p_arti varchar(4), p_cantidad int, out resultado int) 
begin
declare v_existencias int;
declare v_cod_art varchar(4);
declare exit handler for sqlexception
begin
rollback;
    set resultado=0;
end;
select cod_articulo, existencias
into v_cod_art, v_existencias
from articulos
where cod_articulo=p_arti
for update;
if v_cod_art is null then
set resultado=-1;
else
start transaction;
    if p_cantidad > v_existencias then
set resultado=-2;
        rollback;
else
update articulos set existencias=v_existencias-p_cantidad
        where cod_articulo=p_arti;
        commit;
        set resultado=1;
end if;
end if;
end $$
delimiter ;

Comprobaciones:
(antes)
---






---
 (después)


Pregunta 2 

/*mi versión*/
delimiter $$
drop trigger if exists pregunta2 $$
create trigger pregunta2
before delete on pedidos
for each row
begin
/* variables*/
declare v_num_pedido int;
    declare v_enviado char;
declare v_precio_unidad decimal(8,2);
declare v_unidades int;
declare v_cod_articulo char(4);
declare v_ultima_fila int default 0;
/* cursor */
declare detalles_cursor cursor for
select unidades, cod_articulo
from detalle_pedidos
where cod_pedido=v_num_pedido
        for update;
/* control de cursor */
declare continue handler for not found
set v_ultima_fila=1;
/* abre cursor */
select num_pedido, enviado
    into v_num_pedido, v_enviado
    from pedidos
    where num_pedido=old.num_pedido;
open detalles_cursor;
detalles_c : loop
set v_ultima_fila=0;
fetch detalles_cursor into v_unidades, v_cod_articulo;
if v_ultima_fila=1 or v_enviado='S' then
leave detalles_c;
end if;
update articulos set existencias=existencias+v_unidades where cod_articulo=v_cod_articulo;
end loop detalles_c;
close detalles_cursor;
    delete from detalle_pedidos where cod_pedido=old.num_pedido;
end $$

delimiter ;

/* respuesta profesor */
delimiter $$
drop trigger if exists pregunta2 $$
create trigger pregunta2
before delete on pedidos
for each row
begin
declare v_ultima_fila integer default 0;
declare v_cod_pedido integer (3);
declare v_cod_articulo char(4);
declare v_unidades integer(3);
declare pedidos_cursor cursor for
select cod_pedido, cod_articulo, unidades
from detalle_pedidos
where cod_pedido=old.num_pedido
for update;
declare continue handler for not found
set v_ultima_fila=1;
if old.enviado='N' then
open pedidos_cursor;
pedidos_bucle : loop
fetch pedidos_cursor into v_cod_pedido, v_cod_articulo, v_unidades;
            if v_ultima_fila=1 then
leave pedidos_bucle;
end if;
            update articulos set existencias=existencias+v_unidades
            where cod_articulo=v_cod_articulo;
end loop pedidos_bucle;
delete from detalle_pedidos where cod_pedido=old.num_pedido;
close pedidos_cursor;
end if;
end $$

delimiter ;

Comprobaciones:
(antes)


---

---
(después)






Pregunta 3 

/*mi versión con ayuda de compañeros*/ 
delimiter $$
drop function if exists pregunta3 $$
create function pregunta3(e_num_pedido int)
returns decimal(8,2)
begin
/*variables*/
declare v_pedido int;
declare v_cod_articulo char(4);
declare v_precio_unidad decimal(8,2);
declare v_unidades int;
declare v_descuento int;
declare v_ultima_fila int default 0;
declare total decimal(8,2);
declare totalfinal decimal(8,2) default 0;

/*cursor*/
declare articulo_cursor cursor for
select cod_articulo
from detalle_pedidos
where cod_pedido = e_num_pedido;

/*manejador errores*/
declare continue handler for not found
set v_ultima_fila = 1;

/*pedido*/
select count(*)
into v_pedido
from pedidos
where num_pedido = e_num_pedido;

if v_pedido != 1 then
set totalfinal = -1;
        
else

open articulo_cursor;

articulo_c : loop
fetch articulo_cursor into v_cod_articulo;
if v_ultima_fila = 1 then
leave articulo_c;
end if;

select precio_unidad
into v_precio_unidad
from articulos
where cod_articulo = v_cod_articulo;

select unidades
into v_unidades
from detalle_pedidos
where cod_articulo = v_cod_articulo
                and cod_pedido = e_num_pedido;

set total = v_precio_unidad*v_unidades;
set totalfinal=totalfinal+total;
end loop articulo_c;
close articulo_cursor;

select descuento
into v_descuento
from pedidos
where num_pedido = e_num_pedido;

set totalfinal = totalfinal - ((totalfinal*v_descuento)/100);
        
end if;

return totalfinal;

end $$

delimiter ;

/* respuesta profesor */
delimiter $$
drop function if exists pregunta3$$
create function pregunta3 (v_ped int)
returns double
begin
declare existe int;
    declare total_sin double;
    declare v_descuento int;
    select count(*)
into existe
from pedidos
where num_pedido=v_ped;
if existe =0 then
returns(-1);
else
set total_sin=(select sum(d.unidades*a.precio
from articulos a, detalle_pedidos declare
where a.cod_articulo=d.cod_articulo
and d.cod_pedido=v_ped);
set v_descuento=(select descuento
from pedidos
where cod_pedido=v_ped);
returns(total_sin*(1-(v_descuento/100)));
end if;
end $$

delimiter ;

Comprobaciones:
---


---



miércoles, 4 de mayo de 2016

repaso

0

Puedes acceder a la teoría necesaria para hacer los ejercicios,  a los ejercicios y las bases de datos necesarias aquí, aquí y aquí.
1.-






A continuación esta una manera más efectiva de hacer el ejercicio:

delimiter $$
drop function if exists ejercicio2_13 $$
create function ejercicio2_13 (e_reserva int)
returns int
begin
    declare v_precio int;
    declare v_entrada date;
    declare v_salida date;
    declare exit handler for sqlexception
return 1;
    if (select count(*) from reservas where reserva=e_reserva) <> 1 then
return 1;
    else
/* grupo y orecio */
select precio_dia
into v_precio
from precios 
        where grupo= 
        (select grupo_precio
        from apartamentos
where apartamento =
(select apartamento
from reservas
where reserva=e_reserva));
        /* fechas*/
select entrada, salida
into v_entrada, v_salida
from reservas
where reserva=e_reserva;
        /* total*/
return (datediff(v_salida, v_entrada)+1)*v_precio;
end if;
end $$
delimiter ;


2.-

A continuación esta una manera más efectiva de hacer el ejercicio:

delimiter $$
drop trigger if exists ejercicio2_14 $$
create trigger ejercicio2_14 
before update on precios
for each row
begin
if user() <> 'root@localhost' then
signal sqlstate '45000'
        set message_text='usuario incorrecto';
end if;
end $$
delimiter ;


3.-





Etiquetas actuales

BD (67) DEF (64) PROG (64) SQL (44) Java (29) PRACTICAS (20) php (18) DI (16) PRESTASHOP (16) PROGRAMACIÓN WEB (16) HTML (13) SGE (12) ERP (9) CONSULTAS (8) css (8) Linux (5) XML (5) Android (4) PDM (4) C (3) NetBeans (3) PSP (3) SMARTY (3) comandos (3) HOOK (2) POST (2) XSD (2) cURL (2) JS (1) MEDIA-QUERYS (1) PDO (1) RESPONSIVE (1) TPL (1) TRADUCCIÓN (1) app_inventor (1)

Todas las etiquetas

EJER (78) BD (67) DEF (64) PROG (64) SQL (44) c# (40) Programación (39) Ficheros (36) Java (29) bases de datos (21) PRACTICAS (20) lenguajes de marcas (19) AD (18) Entorno de desarrollo (18) php (18) PROCEDIMIENTOS (17) DI (16) FORM (16) PRESTASHOP (16) PROGRAMACIÓN WEB (16) lenguaje C (16) E/R (14) HTML (13) SGE (12) Sistemas informáticos (10) ERP (9) CONSULTAS (8) TRANSACCIONES (8) TRIGGER (8) VISUAL BASIC (8) css (8) FUNCIONES (7) html5 (6) Ada (5) EXAMEN (5) Linux (5) XML (5) estructuras (5) Android (4) DISEÑO (4) INTERFAZ (4) LOG (4) OpenBravo (4) PDM (4) ACTUALIZAR (3) C (3) DIAGRAMA (3) Directorios (3) NEW (3) NOR (3) NetBeans (3) OLD (3) PSP (3) SMARTY (3) comandos (3) css3 (3) AISLAMIENTOS (2) C++ (2) CONTROLERRORES (2) ELIMINAR (2) HOOK (2) INSERTAR (2) INST (2) MULTITABLA (2) POST (2) RECURSIVIDAD (2) SUBCONSULTAS (2) VISTAS (2) XSD (2) cURL (2) punteros (2) AJENA (1) BLOQUEOS (1) Byte (1) CREACION (1) CRM (1) Configuración (1) Controles (1) Datos (1) GOTFOCUS (1) IMAGENES (1) INDICES (1) JS (1) Lenght (1) MEDIA-QUERYS (1) Mingw (1) MonoDeveloped (1) OPTIMISTA (1) PDO (1) PESIMISTA (1) RESPONSIVE (1) SPEAK (1) Scanner (1) Serializacion (1) Streams (1) System (1) TPL (1) TRADUCCIÓN (1) USUARIOS (1) UseSystemPasswordChar (1) app_inventor (1) char (1) examenes (1) libreoffice (1) make (1) redes (1)