Ошибка ora 06508

Это поведение свазано с состоянем пакета. Обратимся к подглаве Package State:

The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state.

If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.

Если в пакете определена как минимум одна переменная, константа или курсор, то пакет после инициализаци получает состояние, которое сохраняется до окончания сессии. Состояние пакета может стать недействительным, одной из причин этого является рекомпиляция пакета:

The package body is recompiled.

If the body of an instantiated, stateful package is recompiled (either explicitly, with the «ALTER PACKAGE Statement», or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.

After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it. Therefore, previous changes to the package state are lost.

После возникновения ошибки, пакеты автоматически реинициализируются, старое их состояние теряется и появляется новое.

Возможное решение, пересмотреть дизайн кода и убрать все переменные, константы или курсоры, объявленные вне функций или процедур, другими словами создать пакет без состояния. Но ничего страшного, если это не предоставляется возможным, при повторном запуске ошибка не должна возникнуть.

Воспроизводимый пример:

create or replace package pack1 as
    val varchar2 (8) := 'pack';
end;
/
create or replace package pack2 as
    function foo return varchar2;
end;
/
create or replace package body pack2 as 
    function foo return varchar2 is
    begin 
        return pack1.val||'2';
    end;
end;
/
select pack2.foo from dual;

FOO
--------
pack2  

В другой сессии заново скомпилируем пакет:

alter package pack1 compile;

Package altered.

Теперь, в первой сессии вызов вызовет ошибку, так как состояние пакета pack1 потеряно:

select pack2.foo from dual;

Error report -
ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package "DB.PACK1" has been invalidated
ORA-04065: not executed, altered or dropped package "DB.PACK1"
ORA-06508: PL/SQL: could not find program unit being called: "DB.PACK1"
ORA-06512: at "DB.PACK2", line 4

select pack2.foo from dual;

FOO
--------
pack2

oracle tutorial webinars

ORA-06508

As a database manager delves further and further into their duties of constructing database materials for their company, several files and processes, both big and small, will start to seem like ancient history. Typically, this is fine as we create and store procedures just for that purpose; we want to be able to instantly recall past constructions and signal them at ease.
However, there are times when we create and store information in a database that, over time, becomes either incompatible with newly designed additions or corrupted. We are then forced to correct these past mistakes and adapt them to current requirements. The ORA-06508 is an error indicative of this type of situation in which maintenance must be performed on a past design to ready it for the up-to-date database needs.

The Problem

The ORA-06508 is an error deriving from a program unit being called and not being found. What this means is that the user tried to call a procedure that was not available due to the procedure being dropped or modified in an incompatible manner. It can also occur when the procedure or program was compiled, but contained errors.

If using the OWB (Oracle warehouse builder), a tool for managing and integrating data, in addition to other SQL operations, you can trigger the ORA-06508 error when one of the individual units within the program has not been appropriately compiled. It can also result from the program not being located, which indicates a problem with the $PATH environment variable.

The Solution

In order to correct this error, the user needs to check all programs referenced in an action. This will also included all package bodies, making sure the programs exist in full and are compatible with the action. You can run a query to discover any invalid objects or procedures that look like the following:

select

comp_id,
comp_name,
version,
status,
namespace,
schema

from

dba_registry;

In the event that the user finds that the procedure has been dropped, trying to re-create the stored procedure can provide a simple fix. Additionally, if the stored procedure was compiled with errors, the user can correct the errors and proceed accordingly.

In some rare instances, the user may receive an ORA-06508 error and, when the user ends the current session and opens a new session, the error will disappear. Typically this error will be accompanied in a stack with several other errors such as the ORA-04068 and ORA-04061, which reveal that existing states of packages have been discarded. If the values of variables and constants that comprise a package are at least one in number, then a package is stateful; otherwise, it is stateless. If a stateful package is recompiled later on, the next version of the package will cause Oracle to discard the existing package state and trigger the ORA-04068. It is rare that the user will need a package to be stateful, so go back to the package and see if anything you stated for variables and constants is necessary to continue. By doing this, the next time the procedure is run an error will not be triggered.

Looking forward

For the most part, by revisiting the logs in the database and running the aforementioned query to specify the origins of the error, an ORA-06508 can be resolved. The ‘select’ portion of the query will return any information needed to successfully uncover what is causing the error. From there, the user can adjust the portion of information and update accordingly. If there are still concerns remaining after implementing these corrections or if further information on concepts such as package states is needed, it is always recommended to contact a licensed Oracle consultant for in-depth inquiries.

Я использую оракул 10g и жабу 11.5. Я пытаюсь вызвать api из анонимного блока.

Если я перекомпилирую api после добавления dbms_output.put_line, а затем попытаюсь выполнить анонимный блок, он отобразит ошибку как

"ORA-06508: PL/SQL: could not find program unit being called".

Однако, если я завершаю текущий сеанс и открываю новый сеанс, анонимный блок будет выполнен с ошибкой.

Из-за этой проблемы, я вынужден повторно подключать сеанс каждый раз, когда я вношу изменения в API.
Может ли кто-нибудь помочь, если эта проблема может быть решена путем создания любых конфигураций на уровне жабы или базы данных.

4b9b3361

Ответ 1

Я подозреваю, что вы сообщаете только о последней ошибке в стеке:

ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"

Если это так, потому что ваш пакет неактивен:

Значения переменных, констант и курсоров, которые пакет объявляет (в своем описании или в своем теле) его пакет состояние. Если пакет PL/SQL объявляет хотя бы одну переменную, константу, или курсором, тогда пакет stateful; в противном случае это безстоящий.

При перекомпиляции состояние теряется:

Если тело экземпляра, пакет с сохранением состояния перекомпилирован (либо явно, с выражением «ALTER PACKAGE Statement», или неявно), следующий вызов подпрограммы в пакете вызывает Oracle Database отказаться от существующего состояния пакета и повысить исключение ОР-04068.

После того, как PL/SQL вызывает исключение, ссылка на пакет вызывает База данных Oracle для повторной инициализации пакета, который повторно инициализирует это…

Вы не можете избежать этого, если ваш пакет имеет состояние. Я думаю, что довольно редко нужно, чтобы пакет был сдержанным, поэтому вы должны пересмотреть все, что вы заявили в пакете, но вне функции или процедуры, чтобы увидеть, действительно ли это необходимо на этом уровне. Так как вы на 10g, это включает в себя константы, а не только переменные и курсоры.

Но последний абзац из цитированной документации означает, что в следующий раз, когда вы ссылаетесь на пакет в том же сеансе, вы не получите ошибку, и она будет работать как обычно (пока вы не перекомпилируете снова).

Ответ 2

похоже, что открытие нового сеанса — это ключ.

см. этот ответ.

и вот удивительное объяснение этой ошибки

Ответ 3

Основываясь на предыдущих ответах. Я решил проблему, удалив глобальную переменную на уровне пакета до процедуры, поскольку в моем случае не было никакого воздействия.

Оригинал script был

create or replace PACKAGE BODY APPLICATION_VALIDATION AS 

V_ERROR_NAME varchar2(200) := '';

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Переписал то же самое без глобальной переменной V_ERROR_NAME и перешел на процедуру под уровнем пакета как

Измененный код

create or replace PACKAGE BODY APPLICATION_VALIDATION AS

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS

**V_ERROR_NAME varchar2(200) := '';** 

BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Ответ 4

Я перекомпилировал спецификацию пакета, хотя изменение было только в теле пакета. Это решило мою проблему

April 29, 2021

I got ” ORA-06508: PL/SQL: could not find program unit being called ” error in Oracle database.

ORA-06508: PL/SQL: could not find program unit being called

Details of error are as follows.

ORA-06508: PL/SQL: could not find program unit being called.

Cause: An attempt was made to call a stored program that could not be found.
The program may have been dropped or incompatibly modified, or have compiled with errors.

Action: Check that all referenced programs, including their package bodies,
exist and are compatible.



PL/SQL: could not find program unit being called

This ORA-06508 errors are related with the stored procedure, the stored procedure you run could not be found.

The issue is caused by unpublished bug 7284151, which relates to a new feature introduced in 11g called fast validation. The purpose of  fast validation is to speed up recompilation by attempting to detect only those objects which strictly needed to be recompiled.

This issue is documented in Note 1192068.1 “Recreating An Existing Package Generates Timestamps Out Of Sync Which Causes ORA-6508”.

To check if you have timestamp discrepancies on your instance that are causing the error(s) run the
following SQL query.

   alter session set nls_date_format='dd-mon-yy hh24:mi:ss';

   select do.name dname, po.name pname, p_timestamp, po.stime p_stime
   from sys.obj$ do, sys.dependency$ d, sys.obj$ po
  where p_obj#=po.obj#(+)
  and d_obj#=do.obj#
  and do.status=1 /*dependent is valid*/
  and po.status=1 /*parent is valid*/
  and po.stime!=p_timestamp /*parent timestamp does not match*/
  and do.type# not in (28,29,30) /*dependent type is not java*/
  and po.type# not in (28,29,30) /*parent type is not java*/
  order by 2,1;

Check the output of the query for the package name found in your error. If this package is found then this is most likely the cause of the error(s).

Another sign of this issue is that the output of the Diagnostic: Apps Check program shows compiled versions of packages that are lower than what is found on the server.

To solve this error, Perform the following as SYSDBA:

1. ALTER SYSTEM set "_disable_fast_validate"=TRUE scope=spfile;

2. Shut down the database:

   SHUTDOWN IMMEDIATE

3. Start the database in upgrade mode:

   STARTUP UPGRADE

4. Oracle provides scripts in $ORACLE_HOME/rdbms/admin that, when run as sys, will invalidate and re-validate all PL/SQL objects so any timestamp mismatches should be resolved. The script utlirp.sql invalidates all PL/SQL based objects, recreates STANDARD and DBMS_STANDARD, invalidates all views and synonyms dependent on now invalid objects and then does some clean up. The script utlrp.sql calls UTL_RECOMP.RECOMP_PARALLEL which performs dependency based recompilation, in parallel where resources allow. Please use these two scripts:

a) Invalidate all the objects – utlirp.sql

b) Recompile all the objects – utlrp.sql

5. ALTER SYSTEM set "_disable_fast_validate"=FALSE scope=spfile;

6. Shut down the database:

   SHUTDOWN IMMEDIATE

7. Start the database:

   STARTUP

8. Retest the issue.

Note: One customer reported the above actions took about 8 hours. Manually recompiling the affected files shown in the output of the SQL query should work as well, but this will be a labor intensive process if the list is extensive.

Do you want to learn Oracle Database for Beginners, then read the following articles.

Oracle Tutorial | Oracle Database Tutorials for Beginners ( Junior Oracle DBA )

About Mehmet Salih Deveci

I am Founder of SysDBASoft IT and IT Tutorial and Certified Expert about Oracle & SQL Server database, Goldengate, Exadata Machine, Oracle Database Appliance administrator with 10+years experience.I have OCA, OCP, OCE RAC Expert Certificates I have worked 100+ Banking, Insurance, Finance, Telco and etc. clients as a Consultant, Insource or Outsource.I have done 200+ Operations in this clients such as Exadata Installation & PoC & Migration & Upgrade, Oracle & SQL Server Database Upgrade, Oracle RAC Installation, SQL Server AlwaysOn Installation, Database Migration, Disaster Recovery, Backup Restore, Performance Tuning, Periodic Healthchecks.I have done 2000+ Table replication with Goldengate or SQL Server Replication tool for DWH Databases in many clients.If you need Oracle DBA, SQL Server DBA, APPS DBA,  Exadata, Goldengate, EBS Consultancy and Training you can send my email adress [email protected].-                                                                                                                                                                                                                                                 -Oracle DBA, SQL Server DBA, APPS DBA,  Exadata, Goldengate, EBS ve linux Danışmanlık ve Eğitim için  [email protected] a mail atabilirsiniz.

ORA-06508: PL/SQL: could not find program unit being called

Причины возникновения:

Переопределение большого пакета или процедуры.

Ошибка может возникать в двух случаях:

  1. Переопределяется большой пакет или процедура. Объект приобретает статус инвалидного. После приведения объекта к нормальному статусу, текущие сеансы вызывающие этот пакет будут получать данную ошибку в течении периода действия всего сеанса. Ошибка возникает из-за сброса состояния пакета в исходное состояние при переопределении.
  2. Переопределяется большой пакет или процедура. Объект приобретает статус инвалидного. После приведения объекта к нормальному статусу, все сеансы (в том числе и новые )вызывающие этот пакет будут получать данную ошибку. Ошибка возникает из-за нехватки свободных непрерывных блоков памяти в фрагментированном разделяемом пуле для загрузки пакета
Действия:

Возможны следующие варианты:

  1. Завершить текущую сессию и начать новую.
  2. Разбить большой пакет на более мелкие пакеты.
  3. Очистить разделяемый пул (ALTER SYSTEM FLUSH SHARED_POOL)
  4. Закрепить пакет в разделяемом пуле (ALTER SYSTEM FLUSH SHARED_POOL)

Курсы английского языка Бутово

Понравилась статья? Поделить с друзьями:
  • Ошибка lci на стиральной машинке самсунг
  • Ошибка err 00001 счетчик цэ2726а
  • Ошибка ora 06413 соединение не открыто
  • Ошибка ora 01401
  • Ошибка launcher error left 4 dead 2