Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle functions: How to pass a table name as parameter, and use a cursor result as a table name?

I need help with this oracle function I am trying to create. Basically what I want to do is pass in the name of a table, and return the maximum value of the column which is the variable table name + '_ID' So it would look like this (tableName)_ID

Here's what I've tried (But I can't get it to even work):

CREATE OR REPLACE FUNCTION RETURN_ID(tableName IN varchar2)
return int
IS 
   curResult varchar2;

   cursor cur1 is
       SELECT column_name
       FROM all_tab_cols
       WHERE table_name = tableName
       AND column_name like '%_ID';

BEGIN

   OPEN cur1;
   FETCH cur1 INTO curResult;
   CLOSE cur1;

   SELECT MAX(curResult) AS MaxID
   FROM tableName;

   RETURN maxID;
END RETURN_ID;
like image 226
merp Avatar asked Oct 15 '25 04:10

merp


1 Answers

Replace

SELECT MAX(curResult) AS MaxID
FROM tableName;

with

execute immediate 
  'select max(' || curResult || ')' ||
  '  from ' || tableName 
  into MaxID;

Whenever you want to dynamically change table or column names in a select statement, there almost always is no other way than to resort to execute immediate statements.

like image 55
René Nyffenegger Avatar answered Oct 17 '25 16:10

René Nyffenegger