Gunakan kamus data untuk membuat pernyataan SQL yang memilih kolom yang benar. Gunakan SQL dinamis untuk membuka refkursor ke pernyataan itu, dan kembalikan kursor dari fungsi.
Contoh Skema
create table tab_1 as
select '00001' id, 'Q0' quarter, 2 risk from dual union all
select '00001' id, 'Q1' quarter, 3 risk from dual union all
select '00001' id, 'Q2' quarter, 1 risk from dual union all
select '00001' id, 'Q3' quarter, 1 risk from dual union all
select '00001' id, 'Q4' quarter, 2 risk from dual;
create table tab_2 as
select '00001' id, 'ACTIVE' status from dual union all
select '00002' id, 'PURGED' status from dual union all
select '00003' id, 'ACTIVE' status from dual union all
select '00004' id, 'ACTIVE' status from dual;
Fungsi
create or replace function get_results(p_id number) return sys_refcursor is
v_sql varchar2(32767);
v_refcursor sys_refcursor;
begin
--Get SQL statement.
select
'select ' ||
listagg(column_name, ',') within group (order by column_id) ||
' from ' || table_name
into v_sql
from user_tab_columns
where table_name = 'TAB_' || p_id
and column_id <= 2
group by table_name;
open v_refcursor for v_sql;
return v_refcursor;
end;
/
Memanggil Fungsi
Fungsi harus bekerja selama aplikasi memahami refkursor. Di bawah ini adalah contoh SQL*Plus versi terbaru:
SQL> select get_results(1) from dual;
GET_RESULTS(1)
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
ID QU
----- --
00001 Q0
00001 Q1
00001 Q2
00001 Q3
00001 Q4