Question : Dynamic SQL for Nested Cursors/Loops

Hello,

I have two cursors that I am using in my PL/SQL procedure.  For the nested cursor, I need to pass it the column name to look at.  For example,

My first cursor will select 10 columns into variables; we'll call them:
v_col1, v_col2, v_col3, etc.

Then, for each of those variables, I call my nested cursor, but the columns I used in the nested cursor will be based on one of the above variables.  For example, for v_col1, I want to execute this cursor:

select distnct col1, NTILE(10) over (order by col1 desc ) as DECILE_RANK from table1 where col1 is not null order by DECILE_RANK desc;

and for v_col2, I want to execute this cursor:

select distnct col2, NTILE(10) over (order by col2 desc ) as DECILE_RANK from table1 where col2 is not null order by DECILE_RANK desc;;

..and so on.  So basically, the nested cursor is essentially the same, except the select statement and where clause will vary based on each of my main variables.

Rather than have 10 distinct nested cursors, I'd like to turn the nested cursor into something like this and dynamically pass the column names:

select v_columnname, NTILE(10) over (order by v_columnname desc) as DECILE_RANK from table1 where v_columnname is not null order by DECILE_RANK desc;

Is this possible?  If so, could someone please provide me some pointers/sample code of how to do this?

Thanks!

Answer : Dynamic SQL for Nested Cursors/Loops

1:
2:
3:
4:
5:
6:
declare
 s_sql    varchar2(200);
.....
 s_sql := 'select ' || v_columnname || ' NTILE(10) over (order by ' || v_columnname || ' desc) as DECILE_RANK from table1 where ' || v_columnname || ' is not null order by DECILE_RANK desc;'
 execute immediate s_sql;
.....
Random Solutions  
 
programming4us programming4us