包的初始化部分 [英] Initialization section of the package

查看:99
本文介绍了包的初始化部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是包装规格:

CREATE OR REPLACE PACKAGE employee_info
IS
  PROCEDURE p;

  FUNCTION f RETURN BOOLEAN;

END employee_info;

这是程序包主体:

CREATE OR REPLACE PACKAGE body employee_info
IS
  PROCEDURE p IS
  BEGIN
    dbms_output.put_line('This is procedure');
    dbms_output.put_line(chr(10));
  END;

  FUNCTION f RETURN BOOLEAN IS
  BEGIN
    dbms_output.put_line('This is function ');
    dbms_output.put_line(chr(10));
    RETURN true;
  END;

BEGIN
  dbms_output.put_line('This is the initialization section of package body');
END employee_info;

何时应使用该程序包的初始化部分?

When should I use this initialization section of the package?

如上例所示,当我第一次执行代码时,只有我可以看到程序包主体的begin..end已执行,而对于其余的调用,则不执行.

As in the above example, when I first execute the code then only i can see that begin..end of package body is executed and for rest of call it is not executed.

我正在使用以下语句执行过程和功能:

I am executing the procedure and function using below statements:

 execute employee_info.p;

    declare
      p1 boolean;
    begin
      p1 := employee_info.f;
    end;

推荐答案

在初始化包时,将执行名称为包初始化"的包初始化部分.在建立会话后或(重新)编译程序包后执行程序包中的第一个过程/功能时,会发生这种情况.目的是初始化可以在会话生存期内使用的程序包的全局状态.所有程序包全局变量都将保留,您以后可以访问它们.

Package initialization section as the name suggest is executed when package is initialized. This happens when first procedure/function from the package is executed after session is established or after package is (re)compiled. The purpose is to initialize the global state of the package that can be used during session lifetime. All package global variables are kept and you can access them later.

示例:

HUSQVIK@hq_pdb_tcp> CREATE OR REPLACE PACKAGE test_package
  2  IS
  3     PROCEDURE foo;
  4  END;
  5  /

Package created.

HUSQVIK@hq_pdb_tcp> CREATE OR REPLACE PACKAGE BODY test_package
  2  IS
  3     PROCEDURE foo
  4     IS
  5     BEGIN
  6             DBMS_OUTPUT.PUT_LINE('Procedure executed. ');
  7     END;
  8
  9  BEGIN
 10     DBMS_OUTPUT.PUT_LINE('Package initialized. ');
 11  END;
 12  /

Package body created.

HUSQVIK@hq_pdb_tcp> EXEC test_package.foo
Package initialized.
Procedure executed.

PL/SQL procedure successfully completed.

HUSQVIK@hq_pdb_tcp> EXEC test_package.foo
Procedure executed.

PL/SQL procedure successfully completed.

HUSQVIK@hq_pdb_tcp>

您会看到,在编译程序包之后,将在执行过程foo时执行初始化部分.程序包现在已初始化. foo的任何后续执行仅执行该过程.

You see that after package is compiled the initialization section is executed when procedure foo is executed. The package is initialized now. Any subsequent execution of foo executes only the procedure.

这篇关于包的初始化部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆