从文件执行PL / SQL函数

时间:2015-02-11 17:13:21

标签: oracle plsql sqlplus

我正在使用SQL * Plus并且有一个名为functions.sql的文件,其中包含3个PL / SQL函数:

create or replace function getcustnamebyid (id number) return varchar2(30)
 is
   ...
 begin
   ...
 end;
/

create or replace function getspcommbyid (id number) return float
 is
   ...
 begin
   ...
/

create or replace function iscommok (comm float) return boolean
 is
   ...
 begin
   ...
 end;
/

我试图在driver.sql程序中调用这些函数。我尝试过以下操作,但是我得到了一个 PL / SQL:ORA-00904:" FUNCTIONS"。" GETCUSTNAMEBYID":无效标识符错误。这两个文件位于同一目录中,如何从functions.sql调用driver.sql中定义的函数?程序也会以同样的方式调用吗?

driver.sql:

declare
  name varchar2(30);
  comm float;
  commok boolean;
begin
  select functions.getcustnamebyid(100)
  into name
  from dual;
  dbms_output.put_line('Hi ' || name );
end;
/

4 个答案:

答案 0 :(得分:2)

你不是。

函数是数据库对象;这意味着它已经compiled on the database。在您可以使用首先需要编译它们的函数之前 - 您可以执行此操作来执行SQL * Plus中的.sql文件,例如:

sqlplus username/password@db @ driver.sql

这将创建(或替换它们已存在)数据库中的函数。

在每个函数创建后添加SQL * Plus命令show errors也是值得的,这样如果有任何错误,你可以看到它们。

答案 1 :(得分:2)

在PL / SQL中,必须在要使用它们的上下文中创建函数。通常,这是通过在数据库中创建对象来完成的,因为建议使用其他答案。如果由于某种原因您真的反对创建数据库对象,实际上可以将它们的范围限制为PL / SQL块:

DECLARE
   FUNCTION getcustnamebyid (id NUMBER)
      RETURN VARCHAR2 IS
   BEGIN
      RETURN NULL;
   END;

   name VARCHAR2 (30);
BEGIN
   name := getcustnamebyid (100);
   DBMS_OUTPUT.put_line ('Hi ' || name);
END;
/

您不能以这种方式引用其他文件中的函数,但它允许您在不保留它们的情况下使用这些函数。这种方法的一个警告是,您只能在过程代码中使用这些函数; SQL只能引用作为数据库对象创建的函数。

答案 2 :(得分:1)

问题的根源是您的函数调用

假设我们在模式中创建了函数get_hello_world,scott(标准示例模式)。

SCOTT@erp> 

  1  CREATE OR REPLACE FUNCTION get_hello_world RETURN VARCHAR2
  2  IS
  3  BEGIN
  4    RETURN 'hello world';
  5* END get_hello_world;
SCOTT@erp> /

Function created.

SCOTT@erp> commit;

接下来,我们创建一个driver.sql文件。这是我的例子:

BEGIN
  dbms_output.put_line(scott.get_hello_world);
END;

接下来,我们要在驱动程序文件中调用它:

SCOTT@erp> @driver.sql
  4  /
hello world

PL/SQL procedure successfully completed.

虽然您的新对象scott.get_hello_world是一个类型为function的新数据库对象,但我们不会使用单词" function"来限定我们的调用。

您收到错误PL/SQL: ORA-00904: "FUNCTIONS"."GETCUSTNAMEBYID": invalid identifier,因为未正确引用scott架构get_hello_world中新编译的数据库对象。

最后,如果我们在使用scott数据库帐户时调用它,我们可以使用所有者scott限定我们的调用。

答案 3 :(得分:0)

此聚会迟了,但是您可以“包含”包含某些功能的文件,然后调用它们,例如,

helper_functions.sql

procedure Echo(AValue in varchar2) is
begin
  dbms_output.put_line(AValue);
end;

driver.sql

set serveroutput on
declare
  @@helper_functions.sql
begin
  Echo('hello');
end;
/

这里的输出将是

SQL> @@driver.sql
hello

PL/SQL procedure successfully completed.