Per 12c e versioni successive, puoi utilizzare DBMS_SQL.RETURN_RESULT
aprendo un REFCURSOR
per il PIVOT
dinamico interrogazione.
Ho rimosso il famigerato (+)
sintassi per left join
, usa sempre ANSI join
sintassi.
DECLARE
exam_ids VARCHAR2(255);
x SYS_REFCURSOR;
BEGIN
SELECT
LISTAGG(''''
|| exam_id
|| ''' AS "'
|| exam_name
|| '"',',') WITHIN GROUP(
ORDER BY
exam_id DESC
)
INTO exam_ids
FROM
exam;
OPEN x FOR 'SELECT
*
FROM
(
SELECT
u.user_id,
u.user_name,
e.exam_id,
eu.exam_date
FROM
users u
LEFT JOIN exam_user eu ON u.user_id = eu.user_id
LEFT JOIN exam e ON e.exam_id = eu.exam_id
ORDER BY
u.user_id
)
PIVOT ( MAX ( exam_date )
FOR exam_id
IN ( ' || EXAM_IDS || ' )
)
ORDER BY
1';
dbms_sql.return_result(x);
END;
/
Per 11g, puoi usare una variabile bind e print
comando ( funziona in sqlplus e in sql developer/Toad quando viene eseguito come script (F5))
variable x REFCURSOR -- bind variable declared.
DECLARE
.. -- no need to declare sys_refcursor
BEGIN
..
OPEN :x FOR 'SELECT . --note the change with colon
*
FROM
(
SELECT
..
END;
/
print x