· 8 years ago · Apr 17, 2018, 10:52 AM
1delimiter ;;
2
3drop procedure if exists envidiosos;;
4create procedure envidiosos(in unNombre varchar(10), in unApellido varchar(25))
5comment 'DNI de clientes que han comprado los mismos coches que el cliente parametrizado'
6
7 begin
8 declare fin1 tinyint(1) default 0;
9 declare fin2 tinyint(1) default 0;
10 declare descartado tinyint(1) default 0;
11 declare candidato varchar(10);
12 declare unCocheComprado varchar(3);
13
14 declare c1 cursor for select dni from clientes;
15 declare c2 cursor for select distinct codcoche from ventas where dni in
16 (select dni from clientes where nombre = unNombre and apellido = unApellido);
17 declare continue handler for not found set fin1 = 1;
18 create temporary table tmp_envidiosos(dni varchar(10));
19
20 open c1;
21 repeat
22 fetch c1 into candidato;
23 set fin2 = fin1;
24 if not fin1 then
25 open c2;
26 repeat
27 fetch c2 into unCocheComprado;
28 if not fin1 and not exists (select * from ventas where dni = candidato
29 and codcoche = unCocheComprado) then
30 set descartado = 1;
31 end if;
32 until fin1 or descartado end repeat;
33 close c2;
34
35 if not descartado then
36 insert into tmp_envidiosos values (candidato);
37 end if;
38 set descartado = 0;
39 end if;
40 set fin1 = 0;
41
42 until fin1 end repeat;
43 close c1;
44
45 select * from tmp_envidiosos;
46 drop table tmp_envidiosos;
47 end;;
48
49delimiter ;