Can I access a cursor's column dynamically? I mean by name? something like this:
declare
v_cursor := select * from emp;
begin
FOR reg IN v_cursor LOOP
dbms_output.put_line(**reg['column_name_as_string']**);
end loop;
end;
I know the bold part is not PL/SQL, but I'm looking for something like that and can't find it anywhere.
Thanks!
You can use the package
DBMS_SQL
to create and access cursors with dynamic queries.However it's not really straightforward to access a column by name because the
DBMS_SQL
package uses positioning and in a dynamic query we may not know the order of the columns before the execution.Furthermore, in the context of this question, it appears that we may not know which column we want to display at compile time, we will assume that the column we want to display is given as a parameter.
We can use
DBMS_SQL.describe_columns
to analyze the columns of aSELECT
query after it has been parsed to build a dynamic mapping of the columns. We will assume that all columns can be cast intoVARCHAR2
since we want to display them withDBMS_OUTPUT
.Here's an example:
We can call this procedure with a query known only at run-time:
Use caution with dynamic SQL: it has the same privileges as the user and can therefore execute any DML and DDL statement allowed for this schema.
For instance, the above procedure could be used to create or drop a table:
You mean something like:
It's probably easiest to make the query dynamic if you can.
If you really want to have a hardcoded
SELECT *
and dynamically select a column from that by name, I think you could do that using DBMS_SQL as Vincent suggests, but it will be somewhat more complex.