PL/SQL passing functions as parameters

孤街醉人 提交于 2020-01-11 09:33:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/11130610/pl-sql-passing-functions-as-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!