Question

Is it possible to use dynamic SQL in a FOR statement?

I am using a FOR loop to handle a batch of records from a SELECT statement. However, what if I want the SELECT statement to be framed at run time, such as the table name may be stored in a variable.

for thisRecord as
    select myColumn from MyTable  --can this be dynamic?
do
    .......
end for;

I want something like the following

declare myCursor cursor for stmt;

set dynamicStmt = 'select myColumn from '||varTable;
prepare stmt from dynamicStmt;

for thisRecord as myCursor
do
    ......
end for;
Was it helpful?

Solution

You could simply use FETCH in a loop.

OTHER TIPS

Since no one else answer my question, I guess this means it's impossible to directly use dynamic SQL in FOR statement.

However as said by others, I can use FETCH. Here is another tricky method I find out later, which works in my case.

Use dynamic SQL to create an alias for given table and use this alias in the FOR statement. The only thing you should pay attention is to make sure the alias exists so the procedure can be compiled.

Create or replace procedure MyProcedure(tableName varchar(50))
Begin
  EXECUTE IMMEDIATE 'Drop alias myAlias';
  EXECUTE IMMEDIATE 'Create alias myAlias for '||tableName;

  for thisRecord as
   select * from myAlias
  do
     .........
  end for;
End
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top