Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PL/SQL passing functions as parameters

I've programmed in PL/SQL during half an year and I had the impression it's a quite plain programming language (IMHO). Although I've stumbled upon interesting articles, like this one - Design Patterns in PL/SQL – Interface Injection for even looser coupling, I recommend reading. Talking about dependency injection, I miss an special feature: passing subroutines as parameters. Is it possible? How?

For instance, imagine I have a code like this in javascript:

function tell_me (printer) {
  printer ("hello");
}

tell_me (function () {
  console.log (word);
});

Is it possible to do something similar in PL/SQL?

like image 476
Bolhoso Avatar asked Jun 21 '12 02:06

Bolhoso


1 Answers

You can't pass a function as a parameter directly. The best you could do is use dynamic PL/SQL to execute a function passed in as a string. I do not recommend this. I can see the use of dynamic PL/SQL in a few cases, but this opens you up to all sorts of problems.

DECLARE 
   PROCEDURE inner_function
   IS
   BEGIN
       dbms_output.put_line('Output');
   END;

   PROCEDURE tell_me(parm_function varchar2) 
   IS
   BEGIN
       EXECUTE IMMEDIATE 'BEGIN '||parm_function||'(); END;';
   END;

BEGIN
   tell_me('inner_function');
END;

DBMS_OUTPUT should just have "Output" in the buffer.

This may not work since inner_function may be out of scope. In that case, define the procedure in the schema itself.

like image 176
N West Avatar answered Oct 03 '22 14:10

N West