For 12c og derover kan du bruge DBMS_SQL.RETURN_RESULT
ved at åbne en REFCURSOR
for den dynamiske PIVOT
forespørgsel.
Jeg har fjernet den berygtede (+)
syntaks for left join
, brug altid ANSI join
syntaks.
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;
/
For 11g kan du bruge en bindevariabel og print
kommando (virker i sqlplus og i sql developer/Toad, når den køres som 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