-- 문제 1. 아래의 SQL의 결과를 프로시저로 생성하시오
select sum( decode(d.loc,'NEW YORK', e.sal, null) ) as "NEW YORK",
sum( decode(d.loc,'DALLAS', e.sal, null) ) as "DALLAS",
sum( decode(d.loc,'CHICAGO', e.sal, null) ) as "CHICAGO",
sum( decode(d.loc,'BOSTON', e.sal, null) ) as "BOSTON"
from emp e, dept d
where e.deptno = d.deptno;
-- PL/SQL
create or replace procedure proc_sumsal_by_loc
(p_x out sys_refcursor)
is
l_query varchar2(4000) := 'select ';
v_first number(10) := 1;
begin
for rec in (select distinct loc from dept) loop
if v_first = 1 then
l_query := l_query||'sum(decode(d.loc,'''||rec.loc||''', e.sal, null)) "'||rec.loc||'"' ;
v_first := 0;
else
l_query := l_query||', sum(decode(d.loc,'''||rec.loc||''', e.sal, null)) "'||rec.loc||'"' ;
end if;
end loop;
l_query := l_query||' from emp e, dept d where e.deptno = d.deptno order by d.deptno';
dbms_output.put_line(l_query);
open p_x for l_query;
end;
/
variable x refcursor;
exec proc_sumsal_by_loc(:x);
print x;
-- 결과