



Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!




Le query ricorsive consentono di risolvere diversi casi di lettura dati che implicano l’esecuzione ciclica della medesima query partendo ogni volta dal risultato della precedente esecuzione. Alcuni contesti in cui può tornare utile scrivere una query ricorsiva sono:
Creiamo una tabella in cui per ogni impiegato esiste un campo che contiene l’ID impiegato del manager. In una struttura aziendale complessa, a sua volta il manager potrebbe avere un altro manager di livello superiore. create or replace table EMP_REL (EMPNO char(6) not null with default primary key, NAME varchar(20) not null with default, MGRNO char(6) not null with default); label on table EMP_REL is 'Employee relations'; label on column EMP_REL ( EMPNO is 'employee id', NAME is 'nome', MGRNO is 'manager id' ); create or replace table EMP_REL (EMPNO char(6) not null with default primary key, NAME varchar(20) not null with default, MGRNO char(6) not null with default); label on table EMP_REL is 'Employee relations'; label on column EMP_REL ( EMPNO is 'employee id', NAME is 'nome', MGRNO is 'manager id' ); create or replace table EMP_REL (EMPNO char(6) not null with default primary key, NAME varchar(20) not null with default,
insert into EMP_REL values ('100000', 'Topolino', ' '), ('100010', 'Pippo', '100000'), ('100020', 'Pluto', '100000'), ('100030', 'Tip', '100010'), ('100040', 'Tap', '100010'), ('100050', 'Qui', '100030'), ('100060', 'Quo', '100030'), ('100070', 'Qua', '100030'), ('100080', 'Cip', '100040'), ('100090', 'Ciop', '100040'); insert into EMP_REL values ('100000', 'Topolino', ' '), ('100010', 'Pippo', '100000'), ('100020', 'Pluto', '100000'), ('100030', 'Tip', '100010'), ('100040', 'Tap', '100010'), ('100050', 'Qui', '100030'), ('100060', 'Quo', '100030'), ('100070', 'Qua', '100030'), ('100080', 'Cip', '100040'), ('100090', 'Ciop', '100040');
Dall’impiegato ‘Pippo’ vogliamo elencare tutti gli impiegati a lui subordinati secondo il loro organigramma: with EMP_LIST ( LEVEL , EMPNO , NAME ) as ( select 1 , EMPNO , NAME from EMP_REL where NAME = 'Pippo' union all select O. LEVEL + 1 , NEXT_LAYER. EMPNO , NEXT_LAYER. NAME from EMP_REL as NEXT_LAYER, EMP_LIST as O where O. EMPNO = NEXT_LAYER. MGRNO ) select LEVEL , NAME from EMP_LIST;