Меню

Ora 20999 описание ошибки

Hi everyone! I’m getting an error and not much luck searching google or on here for suggestions on what to do…

I have a tabular form and I changed my field to be a Select List.

I’ve changed the List of Values Type to be PL/SQL Function Body returning SQL Query, with a source of:

return xxpu.pu_apex_lov_pkg.get_buyer(‘N’);

This is a function that returns sql in a varchar.  I’ve used this method for years.  Now I’m getting this error…any ideas? We just upgraded to 5.1:

ORA-20999: ‘PL/SQL Function Body returning SQL Query’ List of Values not supported for this type! ORA-06512: at «APEX_050100.WWV_FLOW_REG_RPT_COL_DEV_IOT», line 79 ORA-04088: error during execution of trigger ‘APEX_050100.WWV_FLOW_REG_RPT_COL_DEV

If I run the function and put the sql in it’s place it works fine, so I guess that’s what I’ll do for now, but defeats the purpose of having it in one place (the package) to easily maintain.

Here is the sql returned by the function:

  select xxpu.pu_util_pkg.pu_get_buyer_name(agent_id) disp

                   , agent_id   ret      

               from po.po_agents  pa order by disp

I did try creating this form originally as an Interactive Grid but I kept getting Ajax/No Data Found errors so I’ve given up and gone back to the Tabular Form just so I can this project done soon…I did the same thing there for a Select List column and I did not get this error.

Thanks,
Janel

Problem

java.sql.sqlexception:
ORA-20999: 20002 LG_eventi_ah1-1
ORA-00001: unique constraints (BCGAPPS.PK_event) violated

Symptom

java.sql.sqlexception:
ORA-20999: 20002 LG_eventi_ah1-1
ORA-00001: unique constraints (BCGAPPS.PK_event) violated

Cause

The SQL errors occur when the same events are attempted to be updated again into DB. After certain number of attempts, finally these events are moved into the DataLogErrorq. Once the event is logged into the database, the event should be removed from the MQ queue. Looks like here, even though the event is logged into the database, it’s not removed from the queue and as a result, its attempted to be updated again.

Resolving The Problem

Follow these steps to resolve the problem:

  1. Stop the servers
  2. Clear the datalogErrorQ and the datalogQ
  3. Clear router logs
  4. Restart the servers

[{«Product»:{«code»:»SSDKJ8″,»label»:»WebSphere Partner Gateway Enterprise Edition»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»—«,»Platform»:[{«code»:»PF002″,»label»:»AIX»},{«code»:»PF016″,»label»:»Linux»},{«code»:»PF033″,»label»:»Windows»}],»Version»:»6.0;6.0.0.1;6.0.0.2;6.0.0.3;6.0.0.4;6.0.0.5;6.0.0.6;6.0.0.7″,»Edition»:»Advanced»,»Line of Business»:{«code»:»LOB59″,»label»:»Sustainability Software»}}]

Ошибки Оракла ORA-02000 — ORA-02999

В нотной записи PL/SQL допущена нота не той октавы

Группы третьей тысячи ошибок Oracle (по диапазонам кодов от 2000 до 2999):

  • Синтаксические ошибки (продолжение) 2000-2099
  • Ошибки общего прекомпилятора 2100-2199
  • Ошибки ORA-02200 — ORA-02299
  • Ошибки ORA-02300 — ORA-02399
  • Ошибки ORA-02400 — ORA-02499
  • Ошибки ORA-02700 — ORA-02799
  • Ошибки проверки 2800-2899

Синтаксические ошибки (продолжение) 2000-2099

  • ORA-02000 Пропущено ключевое слово [значение]
  • ORA-02001 Пользователь SYS не имеет права создавть индексы с группами свободных списков
  • ORA-02002 Ошибка во время записи информации аудита
  • ORA-02003 Неверный параметр USERENV
  • ORA-02004 Нарушение безопасности
  • ORA-02005 Неявная (-1) длина не верна для этого связывания или определения типа данных
  • ORA-02006 Неправильно упакована строка десятичного формата
  • ORA-02007 Нельзя использовать ALLOCATE или DEALLOCATE опции с REBUILD
  • ORA-02008 Не нулевая шкала указана для нечисловой колонки
  • ORA-02009 Размер указанный для файла не должен быть нулевым
  • ORA-02010 Пропущена строка связи
  • ORA-02011 Дублирующееся имя ссылки на базу данных
  • ORA-02012 Пропущено ключевое слово USING
  • ORA-02013 Пропущено ключевое слово CONNECT
  • ORA-02014 Нет возможности выбрать FOR UPDATE из представления с DISTINCT, GROUP BY и т.д.
  • ORA-02015 Нельзя выбрать FOR UPDATE из удаленной таблицы
  • ORA-02016 Нельзя использовать подзапрос в START WITH на удаленной базе данных
  • ORA-02017 Требуется целочисленное значение
  • ORA-02018 Ссылка на базу данных с тем же именем имеет открытое соединение
  • ORA-02019 Описание соединения для удаленной базы данных не найдено
  • ORA-02020 Используется слишком много ссылок на базу данных
  • ORA-02021 Операции DDL не позволены на удаленной базе данных
  • ORA-02022 Удаленное предложение имеет неоптимизированное представление с удаленным объектом
  • ORA-02023 Предикат START WITH или CONNECT не может быть установлен удаленной базой данных
  • ORA-02024 Ссылка на базу данных не найдена
  • ORA-02025 Все таблицы в предложении SQL должны быть на удаленной базе данных
  • ORA-02026 Пропущено ключевое слово LINK
  • ORA-02027 Многострочный UPDATE для колонки с типом LONG не поддерживается
  • ORA-02028 Выборка количества строк не поддерживается сервером
  • ORA-02029 Пропущено ключевое слово FILE
  • ORA-02030 Выбирать можно только из фиксированных таблиц/представлений
  • ORA-02031 Нет ROWID для фиксированных таблиц или для внешних таблиц
  • ORA-02032 Кластеризованная таблица не может быть использована до того, как построен кластерный индекс.
  • ORA-02033 Кластерный индекс для этого кластера уже существует
  • ORA-02034 Быстрая связка не разрешена
  • ORA-02035 Недопустимая комбинация операции связывания
  • ORA-02035 Недопустимая комбинация условной операции
  • ORA-02036 Слишком много переменных для описания с открытым курсором
  • ORA-02037 Неинициализированное пространство скоростной связки
  • ORA-02038 Определение не позволено для типа массив
  • ORA-02039 Связывание по значению не позволено для типа массив
  • ORA-02040 Удаленная база данных [значение] не поддерживает двухфазную фиксацию
  • ORA-02041 Клиент базы данных не начал транзакцию
  • ORA-02042 Слишком много распределенных транзакций
  • ORA-02043 Текущая транзакция должна быть завершена, перед выполнением [значение]
  • ORA-02044 Менеджер транзакций запрещен доступ: исполняется транзакция
  • ORA-02045 Слишком много локальных сеансов в глобальной транзакции
  • ORA-02046 Распределенная транзакция уже начата
  • ORA-02047 Нельзя объединить, исполняется распределенная транзакция
  • ORA-02048 Попытка начать распределенную транзакцию без регистрации
  • ORA-02049 Истекло время ожидания: распределенная транзакция ожидает блокировки
  • ORA-02050 Транзакция [значение] откачена, несколько удаленных баз данных могут быть под вопросом
  • ORA-02051 Другой сеанс в той же транзакции провален
  • ORA-02052 Удаленная транзакция провалена в [значение]
  • ORA-02053 Транзакция [значение] зафиксированна, несколько удаленных баз данных могут быть под вопросом
  • ORA-02054 Сомнительная транзакция [значение]
  • ORA-02055 Операция распределенного изменения провалена; требуется откат
  • ORA-02056 2PC: [значение]: неверный номер двухфазной фиксации [значение] из [значение]
  • ORA-02057 2PC: [значение]: неверное состояние восстановления номер [значение] из [значение]
  • ORA-02058 Не найдено подготовленных транзакций с идентификатором [значение]
  • ORA-02059 ORA-2PC-CRASH-TEST-[значение] в комментарии фиксации
  • ORA-02060 Указанная выборка для изменения обединение распределенных таблиц
  • ORA-02061 Заблокированная таблица определяет список распределенных таблиц
  • ORA-02062 Распределенное восстановление получило DBID [значение], ожидается [значение]
  • ORA-02063 Предшествующее [значение][значение] из [значение][значение]
  • ORA-02064 Распределенная операция не поддерживается
  • ORA-02065 Недопустимая опция для ALTER SYSTEM
  • ORA-02066 Пропущен или неверный текст DISPATCHERS
  • ORA-02067 Требуется откат транзакции или контрольной точки
  • ORA-02068 Следующая серьезная ошибка из [значение][значение]
  • ORA-02069 Значение параметра global_names, для этой операции, должно быть TRUE
  • ORA-02070 База данных [значение][значение] не поддерживает [значение] в этом контексте
  • ORA-02071 Ошибка инициализации возможностей для удаленной базы данных [значение]
  • ORA-02072 Несоотвествует сетевой протокол распределенной базы данных
  • ORA-02073 Последовательность чисел не поддерживается удаленными изменениями
  • ORA-02074 Нельзя [значение] в распределенной транзакции
  • ORA-02075 Другой экземпляр изменил состояние транзакции [значение]
  • ORA-02076 Последовательность не расположена рядом с изменяемой таблицей или LONG колонкой
  • ORA-02077 Выборка LONG колонок должна быть из там же расположенных таблиц
  • ORA-02078 Неверная установка для ALTER SYSTEM FIXED_DATE
  • ORA-02079 Нет новых сеансов которые могут объеденить фиксирующие распределенные транзакции
  • ORA-02080 Ссылка на базу данных используется
  • ORA-02081 Ссылка на базу данных не открыта
  • ORA-02082 Циклическая ссылка на базу данных должна иметь спецификатор соединения
  • ORA-02083 Имя базы данных содержит недопустимый символ [значение]
  • ORA-02084 Имя базы данных пропущенный компонент
  • ORA-02085 Ссылка на базу данных [значение] соединяется с [значение]
  • ORA-02086 Имя базы данных (ссылки) слишком длинное
  • ORA-02087 Объект заблокирован другим процессом в той же самой транзакции
  • ORA-02088 Опция распределенной базы данных не установлена
  • ORA-02089 COMMIT не позволен в подчиненном сеансе
  • ORA-02090 Сетевая ошибка: неудачный callback+passthru
  • ORA-02091 Транзакция откачена
  • ORA-02092 Вне диапазона слотов в таблице транзакций для распределенной транзакции
  • ORA-02093 TRANSACTIONS_PER_ROLLBACK_SEGMENT [значение] больше чем максимально доступное [значение]
  • ORA-02094 Опция репликации не установлена
  • ORA-02095 Указанный инициализационный параметр не может быть изменен
  • ORA-02096 Указанный инициализационный параметр не изменяемый с этой опцией
  • ORA-02097 Параметр не может быть изменен, потому что указанное значение неверное
  • ORA-02098 Ошибка синтаксического разбора ссылки индекс-таблица (:|)

Ошибки общего прекомпилятора 2100-2199

  • ORA-02100 PCC: недостаточно памяти (т.е. нельзя выделить)
  • ORA-02101 PCC: несовместимый кэш курсора (несовпадение uce/cuc)
  • ORA-02102 PCC: несовместимый кэш курсора (нет вхождения cuc для этого uce)
  • ORA-02103 PCC: несовместимый кэш курсора (ссылка cuc вне диапазона)
  • ORA-02104 PCC: несовместимый кэш хоста (нет доступного cuc)
  • ORA-02105 PCC: несовместимый кэш курсора (нет вхождения cuc в кеше)
  • ORA-02106 PCC: несовместимый кэш курсора (неверный OraCursor nr)
  • ORA-02107 PCC: этот pgm устарела для исполняемых библиотек: пересобирите ее
  • ORA-02108 PCC: для исполняемых библиотек прошел неверный дескриптор
  • ORA-02109 PCC: несовместимый кэш хоста (ссылка sit за пределами диапазона)
  • ORA-02110 PCC: несовместимый кэш хоста (неверный sqi тип)
  • ORA-02111 PCC: ошибка целостности кучи
  • ORA-02112 PCC: SELECT..INTO вернуло слишком много строк
  • ORA-02140 Неверное имя табличного пространства
  • ORA-02141 Неверная опция OFFLINE
  • ORA-02142 Пропущена или неверная опция ALTER TABLESPACE
  • ORA-02143 Неверная опция STORAGE
  • ORA-02144 Для предложения ALTER CLUSTER не указано опций
  • ORA-02145 Пропущена опция STORAGE
  • ORA-02146 SHARED указана несколько раз
  • ORA-02147 Противоречие опций SHARED/EXCLUSIVE
  • ORA-02148 EXCLUSIVE указана несколько раз
  • ORA-02149 Указанный сегмент не существует
  • ORA-02153 Неверная строка пароля в VALUES
  • ORA-02155 Неверный идентификатор табличного пространства DEFAULT
  • ORA-02156 Неверный идентификатор TEMPORARY табличного пространства
  • ORA-02157 Не указано опций для ALTER USER
  • ORA-02158 Неверная опция CREATE INDEX
  • ORA-02159 Установленный DLM не поддерживает этот режим блокировки
  • ORA-02160 Индекс-организованная таблица не может содержать колонки с типом LONG
  • ORA-02161 Неверное значение для MAXLOGFILES
  • ORA-02162 Неверное значение для MAXDATAFILES
  • ORA-02163 Неверное значение для FREELIST GROUPS
  • ORA-02164 Предложение DATAFILE указано более одного раза
  • ORA-02165 Неверная опция для CREATE DATABASE
  • ORA-02166 Указано ARCHIVELOG и NOARCHIVELOG
  • ORA-02167 Предложение LOGFILE указано более одного раза
  • ORA-02168 Неверное значение для FREELISTS
  • ORA-02169 Опция FREELISTS не позволена
  • ORA-02170 Опция FREELIST GROUPS не позволена
  • ORA-02171 Неверное значение для MAXLOGHISTORY
  • ORA-02172 Ключевое слово PUBLIC не подходит для запрещенного потока
  • ORA-02173 Неверная опция для DROP TABLESPACE
  • ORA-02174 Пропущен требуемый номер потока
  • ORA-02175 Неверное имя сегмента отката
  • ORA-02176 Неверная опция для CREATE ROLLBACK SEGMENT
  • ORA-02177 Пропущен требуемый номер группы
  • ORA-02178 Правильный синтаксис: SET TRANSACTION READ { ONLY | WRITE }
  • ORA-02179 Верные опции: ISOLATION LEVEL { SERIALIZABLE | READ COMMITTED }
  • ORA-02180 Неверная опция для CREATE TABLESPACE
  • ORA-02181 Неверная опция для ROLLBACK WORK
  • ORA-02182 Ожидается имя контрольной точки
  • ORA-02183 Верные опции: ISOLATION_LEVEL { SERIALIZABLE | READ COMMITTED }
  • ORA-02184 Ограничение ресурса не позволено в REVOKE
  • ORA-02185 Что то иное от WORK следует COMMIT
  • ORA-02186 Привилегии на ресурсы табличного пространства могут не появляться с другими привилегиями
  • ORA-02187 Неверное указание ограничения
  • ORA-02189 После ON требуется табличное пространство
  • ORA-02190 Ожидается ключевое слово TABLES
  • ORA-02191 Верный синтаксис: SET TRANSACTION USE ROLLBACK SEGMENT имя_сегмента
  • ORA-02192 PCTINCREASE не позволено для предложения хранения сегмента отката
  • ORA-02194 Cлучайная спецификация синтаксической ошибки номер (второстепенная ошибка номер) около [значение]
  • ORA-02195 Попытка создать объект [значение] в табличном пространстве [значение]
  • ORA-02196 PERMANENT/TEMPORARY опция уже указана
  • ORA-02197 Список файлов уже указан
  • ORA-02198 Опция ONLINE/OFFLINE уже указана
  • ORA-02199 Пропущено предложение DATAFILE/TEMPFILE

Ошибки ORA-02200 — ORA-02299

  • ORA-02200 WITH GRANT OPTION не позволено для PUBLIC
  • ORA-02201 Последовательность здесь не позволена
  • ORA-02202 Больше таблиц в этом кластере не разрешено
  • ORA-02203 INITIAL опция не позволена
  • ORA-02204 ALTER, INDEX и EXECUTE не позволены для представлений
  • ORA-02205 Только привилегии SELECT и ALTER верны для последовательностей
  • ORA-02206 Опция INITRANS указана дважды
  • ORA-02207 Неверное значение опции INITRANS
  • ORA-02208 Опция MAXTRANS указана дважды
  • ORA-02209 Неверное значение для опции MAXTRANS
  • ORA-02210 Не указано опций для ALTER TABLE
  • ORA-02211 Неверное значение для PCTFREE или PCTUSED
  • ORA-02212 Опция PCTFREE указана дважды
  • ORA-02213 Опция PCTUSED указана дважды
  • ORA-02214 Опция BACKUP указана дважды
  • ORA-02215 Двойное указание имени табличного пространства в предложении
  • ORA-02216 Ожидается имя табличного пространства
  • ORA-02217 Двойное указание опций хранения
  • ORA-02218 Неверное значение для опции INITIAL
  • ORA-02219 Неверное значение для опции NEXT
  • ORA-02220 Неверное значение для опции MINEXTENTS
  • ORA-02221 Неверное значение для опции MAXEXTENTS
  • ORA-02222 Неверное значение для опции PCTINCREASE
  • ORA-02223 Неверное значение для опции OPTIMAL
  • ORA-02224 Привилегия EXECUTE не позволена для таблиц
  • ORA-02225 Для процедур допустимы только привилегии EXECUTE и DEBUG
  • ORA-02226 Неверное значение MAXEXTENTS (максимально позволенное: [значение])
  • ORA-02227 Неверное имя кластера
  • ORA-02228 Двойное указание SIZE
  • ORA-02229 Неверное значение для опции SIZE
  • ORA-02230 Неверная опция ALTER CLUSTER
  • ORA-02231 Пропущена или неверная опция для ALTER DATABASE
  • ORA-02232 Неверный режим MOUNT
  • ORA-02233 Неверный режим CLOSE
  • ORA-02234 Изменения для этой таблицы уже журнализировано
  • ORA-02235 Журнал изменений для этой таблицы уже для другой таблицы
  • ORA-02236 Неверное имя файла
  • ORA-02237 Неверный размер файла
  • ORA-02238 Список имен файлов имеет различное число файлов
  • ORA-02239 Есть объекты ссылающиеся на эту последовательность
  • ORA-02240 Неверное значение для OBJNO или TABNO
  • ORA-02241 Должно быть EXTENTS (FILE BLOCK SIZE , …)
  • ORA-02242 Не указано опций для ALTER INDEX
  • ORA-02243 Неверная опция ALTER INDEX или ALTER MATERIALIZED VIEW
  • ORA-02244 Неверная опция ALTER ROLLBACK SEGMENT
  • ORA-02245 Неверное имя ROLLBACK SEGMENT
  • ORA-02246 Пропущен текст EVENTS
  • ORA-02247 Не указано опций для ALTER SESSION
  • ORA-02248 Неверная опция для ALTER SESSION
  • ORA-02249 Пропущено или неверное значение для MAXLOGMEMBERS
  • ORA-02250 Пропущено или неверное имя ограничения
  • ORA-02251 Подзапрос здесь не разрешен
  • ORA-02252 Условие проверки ограничения не завершено корректно
  • ORA-02253 Спецификация ограничения здесь не позволена
  • ORA-02254 DEFAULT <выражение> здесь не позволено
  • ORA-02255 NOT NULL не позволено после DEFAULT NULL
  • ORA-02256 Число ссылающихся колонок должно соотвествовать числу колонок на которые ссылаются
  • ORA-02257 Максимальное количество колонок превышено
  • ORA-02258 Задваивающееся или конфликтующее NULL и/или NOT NULL указание
  • ORA-02259 Парное указание UNIQUE/PRIMARY KEY
  • ORA-02260 Таблица может содержать только один первичный ключ
  • ORA-02261 Такой уникальный или первичный ключ уже существует в таблице
  • ORA-02262 ORA-[значение] возникла во время проверки типа колонки выражением по-умолчанию
  • ORA-02263 Требуется указать тип данных для этой колонки
  • ORA-02264 Имя уже используется существующим ограничением
  • ORA-02265 Нет возможности доопределить тип ссылаемой колонки
  • ORA-02266 Уникальные/первичные ключи в таблице ссылающиеся разрешенными внешними ключами
  • ORA-02267 Тип колонки несовместим с типом ссылаемой колонки
  • ORA-02268 Ссылаемая таблица не имеет первичного ключа
  • ORA-02269 Ключевая колонка не может быть с типом данных LONG
  • ORA-02270 Нет совпадающего уникального или первичного ключа в списке колонок
  • ORA-02271 Таблица не имеет такого ограничения
  • ORA-02272 Ограниченная колонка не может быть с типом данных LONG
  • ORA-02273 Этот уникальный/первичный ключ, на него ссылаются некоторые внешние ключи
  • ORA-02274 Дублирование ссылочной целостности
  • ORA-02275 Такая ссылочная целостнеость уже существует в таблице
  • ORA-02276 Значение по-умолчанию не совместимо с типом данных колонки
  • ORA-02277 Неверное имя последовательности
  • ORA-02278 Двойное или конфликтующее указание MAXVALUE/NOMAXVALUE
  • ORA-02279 Двойное или конфликтующее указание MINVALUE/NOMINVALUE
  • ORA-02280 Двойное или конфликтующее указание CYCLE/NOCYCLE
  • ORA-02281 Двойное или конфликтующее указание CACHE/NOCACHE
  • ORA-02282 Двойное или конфликтующее указание ORDER/NOORDER
  • ORA-02283 Нельзя изменить начальный в номер последовательности
  • ORA-02284 Двойное указание INCREMENT BY
  • ORA-02285 Двойное указание START WITH
  • ORA-02286 Не указано опций для ALTER SEQUENCE
  • ORA-02287 Номер последовательности здесь не позволен
  • ORA-02288 Неверный режим OPEN
  • ORA-02289 Последовательность не существует
  • ORA-02290 Проверка целостности ([значение].[значение]) нарушена
  • ORA-02291 Ограничение целостности ([значение].[значение]) нарушено — родительский ключ не найден
  • ORA-02292 Ограничение целостности ([значение].[значение]) нарушено — найдена подчиненная запись
  • ORA-02293 Нельзя проверить ([значение].[значение]) — нарушение целостности
  • ORA-02294 Нельзя разрешить ([значение].[значение]) — ограничение изменено во время проверки
  • ORA-02295 Найдено более чем одно разрешающее/запрещающее предложение для ограничения
  • ORA-02296 Нельзя разрешить ([значение].[значение]) — найдены NULL значения
  • ORA-02297 Нельзя отключить ограничение ([значение].[значение]) — существуют зависимости
  • ORA-02298 Нельзя проверить ([значение].[значение]) — родительские ключи не найдены
  • ORA-02299 Нельзя проверить ([значение].[значение]) — найдены дублирующиеся ключи

Ошибки ORA-02300 — ORA-02399

  • ORA-02300 Неверное значение для OIDGENERATORS
  • ORA-02301 Максимальное значение для OIDGENERATORS 255
  • ORA-02302 Неверное или пропущенное имя типа
  • ORA-02303 Нельзя удалить или заместить тип с зависимыми типом или таблицей
  • ORA-02304 Неверный литерал идентификатора объекта
  • ORA-02305 Для типов допустимы только привилегии EXECUTE, DEBUG и UNDER
  • ORA-02306 Нельзя создать тип, который уже имеет зависимость(и)
  • ORA-02307 Нельзя изменить тип с опцией REPLACE, которая не верна
  • ORA-02308 Неверная опция [значение] для типа колонки
  • ORA-02309 Элементарное нарушение NULL
  • ORA-02310 Превышено максимально позволенное число колонок в таблице
  • ORA-02311 Нельзя изменить тип, имеющий зависимости типа или таблицы, с опцией COMPILE
  • ORA-02313 Тип объекта содержит незапрашиваемый тип [значение] атрибута
  • ORA-02315 Неверное количество аргументов для конструктора по-умолчанию
  • ORA-02320 Неудача в создании хранилища таблицы для вложенной колонки таблицы [значение]
  • ORA-02322 Провалена попытка доступа к хранилищу таблицы вложенной колонки таблицы
  • ORA-02324 Более чем одна колонка указана в списке SELECT, подзапроса THE
  • ORA-02327 Нельзя создать индекс на выражение с типом данных [значение]
  • ORA-02329 Колонка с типом данных [значение] не может быть уникальным или первичным ключем
  • ORA-02330 Спецификация типа данных не позволена
  • ORA-02331 Нельзя создать ограничение на колонку с типом данных [значение]
  • ORA-02332 Нельзя создать индекс на атрибуты этой колонки
  • ORA-02333 Нельзя создать ограничения на атрибуты этой колонки
  • ORA-02334 Нельзя определить тип для колонки
  • ORA-02335 Неверный тип данных для кластерной колонки
  • ORA-02336 Атрибут колонки не может быть доступен
  • ORA-02337 Не объектный тип колонки
  • ORA-02338 Пропущенная или неверная спецификация ограничения колонки
  • ORA-02339 Неверная спецификация колонки
  • ORA-02340 Неверная спецификация колонки
  • ORA-02342 Замещаемый тип содержит ошибки компиляции
  • ORA-02344 Нельзя отменить выполнение на тип с зависимыми таблицами
  • ORA-02345 Нельзя создать представление с колонкой основанной на операторе CURSOR
  • ORA-02347 Нельзя дать привилегии на колонки объектной таблицы
  • ORA-02348 Нельзя создать колонку VARRAY с встроенным LOB
  • ORA-02349 Неверный пользовательский тип — тип неполный
  • ORA-02351 Внутреняя ошибка: [значение]
  • ORA-02352 Ошибка усечения файла
  • ORA-02353 Файлы не из одной операции выгрузки
  • ORA-02354 Ошибка в экспорте/импорте данных [значение]
  • ORA-02355 Ошибка открытия файла
  • ORA-02356 Нет места в базе данных. Загрузка не может быть продолжена
  • ORA-02357 Нет верных файлов снимка
  • ORA-02358 Внутреняя ошибка выборки атрибута [значение]
  • ORA-02359 Внутреняя ошибка установки атрибута [значение]
  • ORA-02360 Критическая ошибка во время инициализации данных импорта/экспорта
  • ORA-02361 Ошибка во время выделения [значение] байт памяти
  • ORA-02362 Ошибка закрытия файла: [значение]
  • ORA-02363 Ошибка чтения из файла: [значение]
  • ORA-02364 Ошибка записи в файл: [значение]
  • ORA-02365 Ошибка поиска в файле: [значение]
  • ORA-02366 Следующие индекс(ы) на таблице [значение] были обработаны:
  • ORA-02367 Ошибка в усеченном файле [значение]
  • ORA-02368 Файл [значение] не является верным для этой операции загрузки
  • ORA-02369 Внимание: Длина поля переменной была усечена
  • ORA-02370 Запись [значение] — Внимание таблица [значение], столбец [значение]
  • ORA-02371 Загрузчик должен быть версии не ниже [значение].[значение].[значение][значение].[значение] для прямого пути
  • ORA-02372 Данные для строки: [значение]
  • ORA-02373 Ошибка синтаксического разбора предложения вставки для таблицы [значение]
  • ORA-02374 Ошибка преобразования при загрузке таблицы [значение].[значение]
  • ORA-02375 Ошибка преобразования при загрузке таблицы [значение].[значение] часть [значение]
  • ORA-02376 Неверный или лишний ресурс
  • ORA-02377 Неверное ограничение ресурса
  • ORA-02378 Задвоенное имя ресурса [значение]
  • ORA-02379 Профиль [значение] уже существует
  • ORA-02380 Профиль [значение] не существует
  • ORA-02381 Нельзя удалить профиль PUBLIC_DEFAULT
  • ORA-02382 Профиль [значение] привязан к пользователю, нельзя удалить без опции CASCADE
  • ORA-02383 Недопустимый стоимостной фактор
  • ORA-02390 Превышение COMPOSITE_LIMIT, вы будите отключены
  • ORA-02391 Превышен одновременный предел SESSIONS_PER_USER
  • ORA-02392 Превышено ограничение сеанса на использование CPU, вы будете отключены
  • ORA-02393 Превышен предел использования CPU
  • ORA-02394 Превышено ограничение на использование IO, вы будете отключены
  • ORA-02395 Превышен предел вызовов на использование I/O
  • ORA-02396 Превышено максимальное время простоя, пожалуйста соединитесь снова
  • ORA-02397 Превышен предел PRIVATE_SGA, вы будите отключены
  • ORA-02398 Превышено использование пространства процедурой
  • ORA-02399 Превышено максимальное время соединения, вы будете отключены

Ошибки ORA-02400 — ORA-02499

  • ORA-02401 Нельзя выполнить EXPLAIN на представлении принадлежащему другому пользователю
  • ORA-02402 Не найдена таблица PLAN_TABLE
  • ORA-02403 Плановая таблица не имеет верный формат
  • ORA-02404 Указанная плановая таблица не найдена
  • ORA-02420 Пропущено предложение авторизации
  • ORA-02421 Пропущен или неверный идентификатор авторизации схемы
  • ORA-02422 Пропущен или неверный элемент схемы
  • ORA-02423 Имя схемы не совпадает с авторизационным идентифиатором
  • ORA-02424 Потенциальная замкнутая ссылочность или неизвестные таблицы для ссылки
  • ORA-02425 Провалено создание таблицы
  • ORA-02426 Провалена выдача привилегий
  • ORA-02427 Создание представления провалено
  • ORA-02428 Не могу добавить ссылку внешнего ключа
  • ORA-02429 Нельзя удалить индекс используемый для уникального/первичного ключа
  • ORA-02430 Нельзя разрешить ограничение [значение] — нет такого ограничения
  • ORA-02431 Нельзя запретить ограничение [значение] — нет такого ограничения
  • ORA-02432 Нельзя разрешить первичный ключ — первичный ключ не определен для таблицы
  • ORA-02433 Нельзя запретить первичный ключ — первичный ключ не определен для таблицы
  • ORA-02434 Нельзя разрешить уникальный ключ [значение] — первичный ключ не определен для таблицы
  • ORA-02435 Нельзя запретить уникальный ключ [значение] — первичный ключ не определен для таблицы
  • ORA-02436 Дата или системная переменная неверно определна в ограничении CHECK
  • ORA-02437 Нельзя проверить [значение.значение] — нарушен первичный ключ
  • ORA-02438 Ограничение колонки не может ссылаться на другие колонки
  • ORA-02439 Уникальный индекс на допускающую задержку постоянную не разрешается
  • ORA-02440 Создание как выборка с ссылочными ограничениями не позволено
  • ORA-02441 Нельзя удалить несуществующий первичный ключ
  • ORA-02442 Нельзя удалить несуществующий уникальный ключ
  • ORA-02443 Нельзя удалить ограничение — несуществующее ограничение
  • ORA-02444 Нельзя разрешить ссылающиеся объекты в ссылочном ограничении
  • ORA-02445 Исключительная таблица не найдена
  • ORA-02446 Провалено CREATE TABLE … AS SELECT — нарушено проверочное ограничение
  • ORA-02447 нельзя отложить ограничение которое не откладываемое
  • ORA-02448 Ограничение не существует
  • ORA-02449 Уникальные/первичные ключи в таблице используются внешними ключами
  • ORA-02450 Неверная хэш опция — пропущено ключевое слово IS
  • ORA-02451 Задвоенная спецификация HASHKEYS
  • ORA-02452 Неверное значение опции HASHKEYS
  • ORA-02453 Задвоенное указание HASH IS
  • ORA-02454 Количество кэш ключей на блок (значение) превышает максимально допустимое [значение]
  • ORA-02455 Количество колонок кластерного ключа должно быть 1
  • ORA-02456 Спецификация HASH IS должна быть NUMBER (*,0)
  • ORA-02457 Опция HASH IS должна определять верную колонку
  • ORA-02458 HASHKEYS должно быть указано для HASH CLUSTER
  • ORA-02459 Значение HASHKEYS должно быть целым положительным числом
  • ORA-02460 Неверная операция индекса на хэш-кластера
  • ORA-02461 Недопустимое использование опции INDEX
  • ORA-02462 Опция INDEX указана дважды
  • ORA-02463 Опция HASH IS указана дважды
  • ORA-02464 Определение кластера не может быть и HASH и INDEX
  • ORA-02465 Недопустимое использование опции HASH IS
  • ORA-02466 Опции SIZE и INITRANS не могут быть изменены для HASH CLUSTERS
  • ORA-02467 Колонка ссылающаяся в выражении не найдена в определении кластера
  • ORA-02468 Константа или системная переменная не верно указана в выражении
  • ORA-02469 Хэш выражение не возвращает число Oracle Number
  • ORA-02470 TO_DATE, USERENV или SYSDATE некорректно использованы в хэш выражении
  • ORA-02471 SYSDATE, UID, USER, ROWNUM или LEVEL некорректно использованы в хэш выражении
  • ORA-02472 PL/SQL функции не позволены в хэш выражениях
  • ORA-02473 Ошибка во время оценки кластерного хэш выражения
  • ORA-02474 Фиксированная хэш зона использует [значение] экстентов, максимум позволено [значение]
  • ORA-02475 Максимальное число цепочки кластерных блоков [значение] было превышено
  • ORA-02476 Нельзя создать индекс пригодный для параллельной прямой загрузки в таблицу
  • ORA-02477 Нельзя выполнить параллельную прямую загрузку для объекта [значение]
  • ORA-02478 Объединение в базовый сегмент переполнит ограничение MAXEXTENTS
  • ORA-02479 Ошибка во время перевода имени файла для параллельной загрузки
  • ORA-02481 Слишком много процессов указано для событий (максимум [значение])
  • ORA-02482 Синтаксическая ошибка в спецификации события [значение]
  • ORA-02483 Синтаксическая ошибка в спецификации процесса [значение]
  • ORA-02486 Ошибка записи в файл отладки [значение]
  • ORA-02490 Пропущен требуемый размер файла в предложении RESIZE
  • ORA-02491 Пропущено требуемое ключевое слово ON или OFF в предложении AUTOEXTEND
  • ORA-02492 Пропущен требуемый размер увеличения файлового блока в предложении NEXT
  • ORA-02493 Неверное изменение размера файла в предложении NEXT
  • ORA-02494 Неверный или пропущенный максимальный размер файла в предложении MAXSIZE
  • ORA-02495 Нельзя изменить размер файла [значение], табличное пространство [значение] только для чтения

Ошибки ORA-02700 — ORA-02799

  • ORA-02700 osnoraenv: Ошибка перевода ORACLE_SID
  • ORA-02701 osnoraenv: ошибка перевода имени изображения Oracle
  • ORA-02702 osnoraenv: ошибка перевода имени изображения orapop
  • ORA-02703 osnpopipe: создание канала провалено
  • ORA-02704 osndopop: ветвление провалено
  • ORA-02705 osnpol: опрос коммуникационного канала провален
  • ORA-02706 osnshs: имя хоста слишком длинное
  • ORA-02707 osnacx: нельзя выделить зону контекста
  • ORA-02708 osnrntab: провалено соединение с хостом, неизвестный ORACLE_SID
  • ORA-02709 osnpop: провалено создание канала
  • ORA-02710 osnpop: ветвление провалено
  • ORA-02711 osnpvalid: запись в канал проверки данных провалена
  • ORA-02712 osnpop: провален malloc
  • ORA-02713 osnprd: провалено получение сообщения
  • ORA-02714 osnpwr: провалена отправка сообщения
  • ORA-02715 osnpgetbrkmsg: сообщение от хоста имеет некорретный тип сообщения
  • ORA-02716 osnpgetdatmsg: сообщение от хоста имеет некорректный формат
  • ORA-02717 osnpfs: записано некорректное число байт
  • ORA-02718 osnprs: ошибка сброса протокола
  • ORA-02719 osnfop: ветвление провалено
  • ORA-02720 osnfop: shmat провален
  • ORA-02721 osnseminit: нельзя создать набор семафора
  • ORA-02722 osnpui: нельзя прервать отправку сообщения к orapop
  • ORA-02723 osnpui: нельзя отправить сигнал разрыва
  • ORA-02724 osnpbr: нельзя прервать отправку сообщения к orapop
  • ORA-02725 osnpbr: нельзя отправить сигнал разрыва
  • ORA-02726 osnpop: ошибка доступа к исполняемым файлам Oracle
  • ORA-02727 osnpop: ошибка доступа к исполняемым файлам orapop
  • ORA-02728 osnfop: ошибка доступа к исполняемым файлам Oracle
  • ORA-02729 osncon: драйвер не в osntab
  • ORA-02730 osnrnf: нельзя найти пользовательскую директорию регистрации
  • ORA-02731 osnrnf: malloc буфера провален
  • ORA-02732 osnrnf: нельзя найти совпадающий псевдоним базы данных
  • ORA-02733 osnsnf: строка базы слишком длинная
  • ORA-02734 osnftt: нельзя сбросить полномочия общей памяти
  • ORA-02735 osnfpm: нельзя сосздать сегмент общей памяти
  • ORA-02736 osnfpm: недопустимый адрес по-умолчанию общей памяти
  • ORA-02737 osnpcl: нельзя дать команду orapop для выхода
  • ORA-02738 osnpwrtbrkmsg: записано некорректное число байт
  • ORA-02739 osncon: псевдоним хоста слишком длинный
  • ORA-02750 osnfsmmap: нельзя открыть файл общей памяти ?/dbs/ftt_.dbf
  • ORA-02751 osnfsmmap: нельзя установить файл общей памяти
  • ORA-02752 osnfsmmap: недопустимый адрес общей памяти
  • ORA-02753 osnfsmmap: нельзя закрыть файл общей памяти
  • ORA-02754 osnfsmmap: нельзя изменить наследование общей памяти
  • ORA-02755 osnfsmcre: нельзя создать вайл общей памяти ?/dbs/ftt_.dbf
  • ORA-02756 osnfsmnam: провал перевод имени
  • ORA-02757 osnfop: fork_and_bind провалено
  • ORA-02758 Размещение внутреннего массива провалено
  • ORA-02759 Нет достаточно доступных дескрипторов запроса
  • ORA-02760 Закрытие файла клиентом провалено
  • ORA-02761 Номер файла отрицательный
  • ORA-02762 Номер файла больше чем допустимый максимум
  • ORA-02763 Не получается отменить как минимум один запрос
  • ORA-02764 Неверный режим пакета
  • ORA-02765 Неверное максимальное количество серверов
  • ORA-02766 Неверный максимум дескрипторов запроса
  • ORA-02767 Как минимум один дескриптор запроса был назначен на сервер
  • ORA-02768 Неверное максимальное количество файлов
  • ORA-02769 Установка заголовка для SIGTERM провалена
  • ORA-02770 Суммарное количество блоков не верно
  • ORA-02771 Недопустимый запрос значения времени
  • ORA-02772 Неверное максимальное время простоя сервера
  • ORA-02773 Неверное максимальное время ожидания клиентом
  • ORA-02774 Неверный запрос списка времени защелки
  • ORA-02775 Неверный запрос завершающего сигнала
  • ORA-02776 Значение для запроса завершающего сигнала превышает максимум
  • ORA-02777 Статистика на журнальную директорию провалена
  • ORA-02778 Имя данное для журнальной директории не верно
  • ORA-02779 Провалена статистика для директории снимков ядра
  • ORA-02780 Имя данное для директории со снимками ядра не верно
  • ORA-02781 Для флага расчета времени дано не верное значение
  • ORA-02782 Обе функции чтения и записи не определены
  • ORA-02783 Обе функции отправки и ижидания не определены
  • ORA-02784 Указан неверный идентификатор общей памяти
  • ORA-02785 Неверный размер буфера общей памяти
  • ORA-02786 Размер необходимый для общей области больше чем размер сегмента
  • ORA-02787 Невозможно выделить память для списка сегмента
  • ORA-02788 Невозможно найти указатель процесса ядра в асинхронной обработке массива
  • ORA-02789 Достигнуто максимальное количество файлов
  • ORA-02790 Имя файла слишком длинное
  • ORA-02791 Невозможно открыть файл для использования с асинхронным вводом/выводом
  • ORA-02792 Нельзя использовать файл в fstat() который используется для асинхронного ввода/вывода
  • ORA-02793 Провалено закрытие асинхронного ввода/вывода
  • ORA-02794 Клиент не может получить ключ для общей памяти
  • ORA-02795 Список запросов пуст
  • ORA-02796 Исполненный запрос не в корректном состоянии
  • ORA-02797 Нет доступных запросов
  • ORA-02798 Неверное количество запросов
  • ORA-02799 Невозможно ответвление знака обработчика

Ошибки проверки 2800-2899

  • ORA-02800 Истекло время ожидания запроса
  • ORA-02801 Истекло время операции
  • ORA-02802 Нет доступных простаивающих серверов в параллельном режиме
  • ORA-02803 Провален возврат текущего времени
  • ORA-02804 Провалено выделение памяти для имени журнального файла
  • ORA-02805 Невозможно установить обработчик для SIGTPA
  • ORA-02806 Невозможно установить обработчик для SIGALRM
  • ORA-02807 Провалено выделение памяти для блоков ввода/вывода
  • ORA-02808 Провалено выделение памяти массива открытых файлов
  • ORA-02809 Буфер перехода не верен
  • ORA-02810 Невозможно создать временное имя файла для файла памяти
  • ORA-02811 Невозможно присоединить сегмент общей памяти
  • ORA-02812 Неверный адрес прикрепления
  • ORA-02813 Невозможно создать временное имя файла в порядке полученного ключа
  • ORA-02814 Невозможно получить общую память
  • ORA-02815 Невозможно присоеденить общую память
  • ORA-02816 Невозможно «убить» процесс
  • ORA-02817 Чтение провалено
  • ORA-02818 Меньшее количество требуемых блоков было прочитано
  • ORA-02819 Запись провалена
  • ORA-02820 Невозможно записать запрошенное количество блоков
  • ORA-02821 Невозможно прочитать запрошенное количество блоков
  • ORA-02822 Неверное смещение блоков
  • ORA-02823 Буфер не выровнен
  • ORA-02824 Запрошенный свободный список пуст
  • ORA-02825 Запрос на свободный список не свободен
  • ORA-02826 Недопустимый размер блока
  • ORA-02827 Неверное имя файла
  • ORA-02828 Свободный список сегментов пуст
  • ORA-02829 Нет доступных сегментов с подходящим размером
  • ORA-02830 Сегмент не может быть разделен — нет доступных свободных сегментов
  • ORA-02831 Провалено освобождение сегментов — пустой список сегментов
  • ORA-02832 Освобождение сегмента провалено — сегмент не в списке
  • ORA-02833 Сервер не может закрыть файл
  • ORA-02834 Сервер не может открыть файл
  • ORA-02835 Сервер не может отправить сигнал клиенту
  • ORA-02836 Невозможно создать временный ключевой файл
  • ORA-02837 Невозможно отцепить временный файл
  • ORA-02838 Невозможно раветвить обработчик сигнала для тревожного сигнала
  • ORA-02839 Синхронизация блоков на диск провалена
  • ORA-02840 Провалено открытие файла журнала клиентом
  • ORA-02841 Сервер «умер» во время запуска
  • ORA-02842 Клиент не может раветвить сервер
  • ORA-02843 Неверное значение для флага ядра
  • ORA-02844 Неверное значение для открытого флага
  • ORA-02845 Неверное значение для флага выбора времени
  • ORA-02846 Неубиваемый сервер
  • ORA-02847 Сервер не останавливается когда есть задержка
  • ORA-02848 Пакет асинхронного ввода/вывода не запущен
  • ORA-02849 Чтение провалено из за ошибки
  • ORA-02850 Файл закрыт
  • ORA-02851 Список запроса пуст, когда не должен быть
  • ORA-02852 Неверное время критической секции
  • ORA-02853 Неверное значение времени в списке защелок сервера
  • ORA-02854 Неверное количество запрошенных буферов
  • ORA-02855 Количество запросов меньше чем количество подчиненных
  • ORA-02875 smpini: Невозможно получить общую память для PGA
  • ORA-02876 smpini: Невозможно присоединитьь общую память для PGA
  • ORA-02877 smpini: Невозможно инициализировать защиту памяти
  • ORA-02878 sou2o: Переменная smpdidini перезаписана
  • ORA-02879 sou2o: Нельзя получить доступ к защищенной памяти
  • ORA-02880 smpini: Нельзя зарегистрировать PGA для защиты
  • ORA-02881 sou2o: Нельзя отменить доступ к защищенной памяти
  • ORA-02882 sou2o: Нельзя зарегистрировать SGA для защиты
  • ORA-02899 smscre: Нельзя создать SGA со свойством Extended Shared Memory

На правах рекламы (см.
условия):


Ключевые слова для поиска сведений о значениях ошибок Oracle в диапазоне ORA-02000 — ORA-02999:

На русском языке: ошибки Oracle, коды оракловых ошибок;

На английском языке: ORA-02000 — ORA-02999.


Страница обновлена 28.09.2022

Яндекс.Метрика


Я использую Oracle Apex и создаю отчет на основе возврата sql из тела plsql.

Вот как выглядит мое утверждение:

DECLARE
    l_query varchar2(1000); 
BEGIN
   l_query := 'SELECT ' || :P10_MYVAR || ' from dual ';
   return l_query;
END;

Я получаю следующее сообщение об ошибке:

ORA-20999: Parsing returned query results in "ORA-20999: Failed to parse SQL query! <p>ORA-06550: line 3, column 25: ORA-00936: missing expression</p>".

Если я попробую без каких-либо переменных связывания, он будет нормально компилироваться:

DECLARE
        l_query varchar2(1000); 
    BEGIN
       l_query := 'SELECT sysdate from dual ';
       return l_query;
    END;

Я не понимаю, почему возникает эта ошибка. Если я запустил команду прямо в базе данных:

SELECT :P10_MYVAR from dual

Это нормально. Почему я получаю эту ошибку?

2 ответа

Лучший ответ

Предположительно, вы имели в виду:

DECLARE
    l_query varchar2(1000); 
BEGIN
   l_query := 'SELECT :P10_MYVAR from dual';
   return l_query;
END;

То есть: вы хотите, чтобы имя параметра было внутри запроса, а не конкатенировано со строкой.

Для той же ошибки при использовании выражения Apex у меня работал следующий запрос

 declare
v_sql varchar2(4000);
begin

  if :P8_TYPE = 'C' then
    return q'~
    select ROWID,
           ID,
           C1,
           TXDATE,
           TRANSACTIONTYPE, 
           DEBIT,
           CREDIT,
           BALANCE 
      from TRANSMASTER
      where 
      TXDATE BETWEEN TO_DATE (:P8_FROMDT, 'mm/dd/yyyy') AND TO_DATE (:P8_TODT, 'mm/dd/yyyy') AND CREDIT > 0; 
    ~';
  else
    return q'~
    select ROWID,
           ID,
           C1,
           TXDATE,
           TRANSACTIONTYPE, 
           DEBIT,
           CREDIT,
           BALANCE 
      from TRANSMASTER
      where 
      TXDATE BETWEEN TO_DATE (:P8_FROMDT, 'mm/dd/yyyy') AND TO_DATE (:P8_TODT, 'mm/dd/yyyy')  AND DEBIT > 0; 
    ~';
  end if;
   
end;


0

Madhusudhan Rao
4 Окт 2020 в 16:48

There is nothing more exhilarating than to be shot at without result. —Winston Churchill

Run-time errors arise from design faults, coding mistakes, hardware failures, and many other sources. Although you cannot anticipate all possible errors, you can plan to handle certain kinds of errors meaningful to your PL/SQL program.

With many programming languages, unless you disable error checking, a run-time error such as stack overflow or division by zero stops normal processing and returns control to the operating system. With PL/SQL, a mechanism called exception handling lets you «bulletproof» your program so that it can continue operating in the presence of errors.

This chapter contains these topics:

  • Overview of PL/SQL Runtime Error Handling

  • Advantages of PL/SQL Exceptions

  • Summary of Predefined PL/SQL Exceptions

  • Defining Your Own PL/SQL Exceptions

  • How PL/SQL Exceptions Are Raised

  • How PL/SQL Exceptions Propagate

  • Reraising a PL/SQL Exception

  • Handling Raised PL/SQL Exceptions

  • Tips for Handling PL/SQL Errors

  • Overview of PL/SQL Compile-Time Warnings

Overview of PL/SQL Runtime Error Handling

In PL/SQL, an error condition is called an exception. Exceptions can be internally defined (by the runtime system) or user defined. Examples of internally defined exceptions include division by zero and out of memory. Some common internal exceptions have predefined names, such as ZERO_DIVIDE and STORAGE_ERROR. The other internal exceptions can be given names.

You can define exceptions of your own in the declarative part of any PL/SQL block, subprogram, or package. For example, you might define an exception named insufficient_funds to flag overdrawn bank accounts. Unlike internal exceptions, user-defined exceptions must be given names.

When an error occurs, an exception is raised. That is, normal execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram. Internal exceptions are raised implicitly (automatically) by the run-time system. User-defined exceptions must be raised explicitly by RAISE statements, which can also raise predefined exceptions.

To handle raised exceptions, you write separate routines called exception handlers. After an exception handler runs, the current block stops executing and the enclosing block resumes with the next statement. If there is no enclosing block, control returns to the host environment.

The following example calculates a price-to-earnings ratio for a company. If the company has zero earnings, the division operation raises the predefined exception ZERO_DIVIDE, the execution of the block is interrupted, and control is transferred to the exception handlers. The optional OTHERS handler catches all exceptions that the block does not name specifically.

SET SERVEROUTPUT ON;

DECLARE
   stock_price NUMBER := 9.73;
   net_earnings NUMBER := 0;
   pe_ratio NUMBER;
BEGIN
-- Calculation might cause division-by-zero error.
   pe_ratio := stock_price / net_earnings;
   dbms_output.put_line('Price/earnings ratio = ' || pe_ratio);

EXCEPTION  -- exception handlers begin

-- Only one of the WHEN blocks is executed.

   WHEN ZERO_DIVIDE THEN  -- handles 'division by zero' error
      dbms_output.put_line('Company must have had zero earnings.');
      pe_ratio := null;

   WHEN OTHERS THEN  -- handles all other errors
      dbms_output.put_line('Some other kind of error occurred.');
      pe_ratio := null;

END;  -- exception handlers and block end here
/

The last example illustrates exception handling. With some better error checking, we could have avoided the exception entirely, by substituting a null for the answer if the denominator was zero:

DECLARE
   stock_price NUMBER := 9.73;
   net_earnings NUMBER := 0;
   pe_ratio NUMBER;
BEGIN
   pe_ratio :=
      case net_earnings
         when 0 then null
         else stock_price / net_earnings
      end;
END;
/

Guidelines for Avoiding and Handling PL/SQL Errors and Exceptions

Because reliability is crucial for database programs, use both error checking and exception handling to ensure your program can handle all possibilities:

  • Add exception handlers whenever there is any possibility of an error occurring. Errors are especially likely during arithmetic calculations, string manipulation, and database operations. Errors could also occur at other times, for example if a hardware failure with disk storage or memory causes a problem that has nothing to do with your code; but your code still needs to take corrective action.

  • Add error-checking code whenever you can predict that an error might occur if your code gets bad input data. Expect that at some time, your code will be passed incorrect or null parameters, that your queries will return no rows or more rows than you expect.

  • Make your programs robust enough to work even if the database is not in the state you expect. For example, perhaps a table you query will have columns added or deleted, or their types changed. You can avoid such problems by declaring individual variables with %TYPE qualifiers, and declaring records to hold query results with %ROWTYPE qualifiers.

  • Handle named exceptions whenever possible, instead of using WHEN OTHERS in exception handlers. Learn the names and causes of the predefined exceptions. If your database operations might cause particular ORA- errors, associate names with these errors so you can write handlers for them. (You will learn how to do that later in this chapter.)

  • Test your code with different combinations of bad data to see what potential errors arise.

  • Write out debugging information in your exception handlers. You might store such information in a separate table. If so, do it by making a call to a procedure declared with the PRAGMA AUTONOMOUS_TRANSACTION, so that you can commit your debugging information, even if you roll back the work that the main procedure was doing.

  • Carefully consider whether each exception handler should commit the transaction, roll it back, or let it continue. Remember, no matter how severe the error is, you want to leave the database in a consistent state and avoid storing any bad data.

Advantages of PL/SQL Exceptions

Using exceptions for error handling has several advantages.

With exceptions, you can reliably handle potential errors from many statements with a single exception handler:

BEGIN
   SELECT ...
   SELECT ...
   procedure_that_performs_select();
   ...
EXCEPTION
   WHEN NO_DATA_FOUND THEN  -- catches all 'no data found' errors

Instead of checking for an error at every point it might occur, just add an exception handler to your PL/SQL block. If the exception is ever raised in that block (or any sub-block), you can be sure it will be handled.

Sometimes the error is not immediately obvious, and could not be detected until later when you perform calculations using bad data. Again, a single exception handler can trap all division-by-zero errors, bad array subscripts, and so on.

If you need to check for errors at a specific spot, you can enclose a single statement or a group of statements inside its own BEGIN-END block with its own exception handler. You can make the checking as general or as precise as you like.

Isolating error-handling routines makes the rest of the program easier to read and understand.

Summary of Predefined PL/SQL Exceptions

An internal exception is raised automatically if your PL/SQL program violates an Oracle rule or exceeds a system-dependent limit. PL/SQL predefines some common Oracle errors as exceptions. For example, PL/SQL raises the predefined exception NO_DATA_FOUND if a SELECT INTO statement returns no rows.

You can use the pragma EXCEPTION_INIT to associate exception names with other Oracle error codes that you can anticipate. To handle unexpected Oracle errors, you can use the OTHERS handler. Within this handler, you can call the functions SQLCODE and SQLERRM to return the Oracle error code and message text. Once you know the error code, you can use it with pragma EXCEPTION_INIT and write a handler specifically for that error.

PL/SQL declares predefined exceptions globally in package STANDARD. You need not declare them yourself. You can write handlers for predefined exceptions using the names in the following list:

Exception Oracle Error SQLCODE Value
ACCESS_INTO_NULL ORA-06530 -6530
CASE_NOT_FOUND ORA-06592 -6592
COLLECTION_IS_NULL ORA-06531 -6531
CURSOR_ALREADY_OPEN ORA-06511 -6511
DUP_VAL_ON_INDEX ORA-00001 -1
INVALID_CURSOR ORA-01001 -1001
INVALID_NUMBER ORA-01722 -1722
LOGIN_DENIED ORA-01017 -1017
NO_DATA_FOUND ORA-01403 +100
NOT_LOGGED_ON ORA-01012 -1012
PROGRAM_ERROR ORA-06501 -6501
ROWTYPE_MISMATCH ORA-06504 -6504
SELF_IS_NULL ORA-30625 -30625
STORAGE_ERROR ORA-06500 -6500
SUBSCRIPT_BEYOND_COUNT ORA-06533 -6533
SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 -6532
SYS_INVALID_ROWID ORA-01410 -1410
TIMEOUT_ON_RESOURCE ORA-00051 -51
TOO_MANY_ROWS ORA-01422 -1422
VALUE_ERROR ORA-06502 -6502
ZERO_DIVIDE ORA-01476 -1476

Brief descriptions of the predefined exceptions follow:

Exception Raised when …
ACCESS_INTO_NULL A program attempts to assign values to the attributes of an uninitialized object.
CASE_NOT_FOUND None of the choices in the WHEN clauses of a CASE statement is selected, and there is no ELSE clause.
COLLECTION_IS_NULL A program attempts to apply collection methods other than EXISTS to an uninitialized nested table or varray, or the program attempts to assign values to the elements of an uninitialized nested table or varray.
CURSOR_ALREADY_OPEN A program attempts to open an already open cursor. A cursor must be closed before it can be reopened. A cursor FOR loop automatically opens the cursor to which it refers, so your program cannot open that cursor inside the loop.
DUP_VAL_ON_INDEX A program attempts to store duplicate values in a database column that is constrained by a unique index.
INVALID_CURSOR A program attempts a cursor operation that is not allowed, such as closing an unopened cursor.
INVALID_NUMBER In a SQL statement, the conversion of a character string into a number fails because the string does not represent a valid number. (In procedural statements, VALUE_ERROR is raised.) This exception is also raised when the LIMIT-clause expression in a bulk FETCH statement does not evaluate to a positive number.
LOGIN_DENIED A program attempts to log on to Oracle with an invalid username or password.
NO_DATA_FOUND A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index-by table.

Because this exception is used internally by some SQL functions to signal that they are finished, you should not rely on this exception being propagated if you raise it within a function that is called as part of a query.

NOT_LOGGED_ON A program issues a database call without being connected to Oracle.
PROGRAM_ERROR PL/SQL has an internal problem.
ROWTYPE_MISMATCH The host cursor variable and PL/SQL cursor variable involved in an assignment have incompatible return types. For example, when an open host cursor variable is passed to a stored subprogram, the return types of the actual and formal parameters must be compatible.
SELF_IS_NULL A program attempts to call a MEMBER method, but the instance of the object type has not been initialized. The built-in parameter SELF points to the object, and is always the first parameter passed to a MEMBER method.
STORAGE_ERROR PL/SQL runs out of memory or memory has been corrupted.
SUBSCRIPT_BEYOND_COUNT A program references a nested table or varray element using an index number larger than the number of elements in the collection.
SUBSCRIPT_OUTSIDE_LIMIT A program references a nested table or varray element using an index number (-1 for example) that is outside the legal range.
SYS_INVALID_ROWID The conversion of a character string into a universal rowid fails because the character string does not represent a valid rowid.
TIMEOUT_ON_RESOURCE A time-out occurs while Oracle is waiting for a resource.
TOO_MANY_ROWS A SELECT INTO statement returns more than one row.
VALUE_ERROR An arithmetic, conversion, truncation, or size-constraint error occurs. For example, when your program selects a column value into a character variable, if the value is longer than the declared length of the variable, PL/SQL aborts the assignment and raises VALUE_ERROR. In procedural statements, VALUE_ERROR is raised if the conversion of a character string into a number fails. (In SQL statements, INVALID_NUMBER is raised.)
ZERO_DIVIDE A program attempts to divide a number by zero.

Defining Your Own PL/SQL Exceptions

PL/SQL lets you define exceptions of your own. Unlike predefined exceptions, user-defined exceptions must be declared and must be raised explicitly by RAISE statements.

Declaring PL/SQL Exceptions

Exceptions can be declared only in the declarative part of a PL/SQL block, subprogram, or package. You declare an exception by introducing its name, followed by the keyword EXCEPTION. In the following example, you declare an exception named past_due:

DECLARE
   past_due EXCEPTION;

Exception and variable declarations are similar. But remember, an exception is an error condition, not a data item. Unlike variables, exceptions cannot appear in assignment statements or SQL statements. However, the same scope rules apply to variables and exceptions.

Scope Rules for PL/SQL Exceptions

You cannot declare an exception twice in the same block. You can, however, declare the same exception in two different blocks.

Exceptions declared in a block are considered local to that block and global to all its sub-blocks. Because a block can reference only local or global exceptions, enclosing blocks cannot reference exceptions declared in a sub-block.

If you redeclare a global exception in a sub-block, the local declaration prevails. The sub-block cannot reference the global exception, unless the exception is declared in a labeled block and you qualify its name with the block label:

block_label.exception_name

The following example illustrates the scope rules:

DECLARE
   past_due EXCEPTION;
   acct_num NUMBER;
BEGIN
   DECLARE  ---------- sub-block begins
      past_due EXCEPTION;  -- this declaration prevails
      acct_num NUMBER;
     due_date DATE := SYSDATE - 1;
     todays_date DATE := SYSDATE;
   BEGIN
      IF due_date < todays_date THEN
         RAISE past_due;  -- this is not handled
      END IF;
   END;  ------------- sub-block ends
EXCEPTION
   WHEN past_due THEN  -- does not handle RAISEd exception
      dbms_output.put_line('Handling PAST_DUE exception.');
   WHEN OTHERS THEN
     dbms_output.put_line('Could not recognize PAST_DUE_EXCEPTION in this scope.');
END;
/

The enclosing block does not handle the raised exception because the declaration of past_due in the sub-block prevails. Though they share the same name, the two past_due exceptions are different, just as the two acct_num variables share the same name but are different variables. Thus, the RAISE statement and the WHEN clause refer to different exceptions. To have the enclosing block handle the raised exception, you must remove its declaration from the sub-block or define an OTHERS handler.

Associating a PL/SQL Exception with a Number: Pragma EXCEPTION_INIT

To handle error conditions (typically ORA- messages) that have no predefined name, you must use the OTHERS handler or the pragma EXCEPTION_INIT. A pragma is a compiler directive that is processed at compile time, not at run time.

In PL/SQL, the pragma EXCEPTION_INIT tells the compiler to associate an exception name with an Oracle error number. That lets you refer to any internal exception by name and to write a specific handler for it. When you see an error stack, or sequence of error messages, the one on top is the one that you can trap and handle.

You code the pragma EXCEPTION_INIT in the declarative part of a PL/SQL block, subprogram, or package using the syntax

PRAGMA EXCEPTION_INIT(exception_name, -Oracle_error_number);

where exception_name is the name of a previously declared exception and the number is a negative value corresponding to an ORA- error number. The pragma must appear somewhere after the exception declaration in the same declarative section, as shown in the following example:

DECLARE
   deadlock_detected EXCEPTION;
   PRAGMA EXCEPTION_INIT(deadlock_detected, -60);
BEGIN
   null; -- Some operation that causes an ORA-00060 error
EXCEPTION
   WHEN deadlock_detected THEN
      null; -- handle the error
END;
/

Defining Your Own Error Messages: Procedure RAISE_APPLICATION_ERROR

The procedure RAISE_APPLICATION_ERROR lets you issue user-defined ORA- error messages from stored subprograms. That way, you can report errors to your application and avoid returning unhandled exceptions.

To call RAISE_APPLICATION_ERROR, use the syntax

raise_application_error(error_number, message[, {TRUE | FALSE}]);

where error_number is a negative integer in the range -20000 .. -20999 and message is a character string up to 2048 bytes long. If the optional third parameter is TRUE, the error is placed on the stack of previous errors. If the parameter is FALSE (the default), the error replaces all previous errors. RAISE_APPLICATION_ERROR is part of package DBMS_STANDARD, and as with package STANDARD, you do not need to qualify references to it.

An application can call raise_application_error only from an executing stored subprogram (or method). When called, raise_application_error ends the subprogram and returns a user-defined error number and message to the application. The error number and message can be trapped like any Oracle error.

In the following example, you call raise_application_error if an error condition of your choosing happens (in this case, if the current schema owns less than 1000 tables):

DECLARE
   num_tables NUMBER;
BEGIN
   SELECT COUNT(*) INTO num_tables FROM USER_TABLES;
   IF num_tables < 1000 THEN
      /* Issue your own error code (ORA-20101) with your own error message. */
      raise_application_error(-20101, 'Expecting at least 1000 tables');
   ELSE
      NULL; -- Do the rest of the processing (for the non-error case).
   END IF;
END;
/

The calling application gets a PL/SQL exception, which it can process using the error-reporting functions SQLCODE and SQLERRM in an OTHERS handler. Also, it can use the pragma EXCEPTION_INIT to map specific error numbers returned by raise_application_error to exceptions of its own, as the following Pro*C example shows:

EXEC SQL EXECUTE
   /* Execute embedded PL/SQL block using host 
      variables my_emp_id and my_amount, which were
      assigned values in the host environment. */
   DECLARE
      null_salary EXCEPTION;
      /* Map error number returned by raise_application_error
         to user-defined exception. */
      PRAGMA EXCEPTION_INIT(null_salary, -20101);
   BEGIN
      raise_salary(:my_emp_id, :my_amount);
   EXCEPTION
      WHEN null_salary THEN
         INSERT INTO emp_audit VALUES (:my_emp_id, ...);
   END;
END-EXEC;

This technique allows the calling application to handle error conditions in specific exception handlers.

Redeclaring Predefined Exceptions

Remember, PL/SQL declares predefined exceptions globally in package STANDARD, so you need not declare them yourself. Redeclaring predefined exceptions is error prone because your local declaration overrides the global declaration. For example, if you declare an exception named invalid_number and then PL/SQL raises the predefined exception INVALID_NUMBER internally, a handler written for INVALID_NUMBER will not catch the internal exception. In such cases, you must use dot notation to specify the predefined exception, as follows:

EXCEPTION
   WHEN invalid_number OR STANDARD.INVALID_NUMBER THEN 
      -- handle the error
END;

How PL/SQL Exceptions Are Raised

Internal exceptions are raised implicitly by the run-time system, as are user-defined exceptions that you have associated with an Oracle error number using EXCEPTION_INIT. However, other user-defined exceptions must be raised explicitly by RAISE statements.

Raising Exceptions with the RAISE Statement

PL/SQL blocks and subprograms should raise an exception only when an error makes it undesirable or impossible to finish processing. You can place RAISE statements for a given exception anywhere within the scope of that exception. In the following example, you alert your PL/SQL block to a user-defined exception named out_of_stock:

DECLARE
   out_of_stock   EXCEPTION;
   number_on_hand NUMBER := 0;
BEGIN
   IF number_on_hand < 1 THEN
      RAISE out_of_stock; -- raise an exception that we defined
   END IF;
EXCEPTION
   WHEN out_of_stock THEN
      -- handle the error
      dbms_output.put_line('Encountered out-of-stock error.');
END;
/

You can also raise a predefined exception explicitly. That way, an exception handler written for the predefined exception can process other errors, as the following example shows:

DECLARE
   acct_type INTEGER := 7;
BEGIN
   IF acct_type NOT IN (1, 2, 3) THEN
      RAISE INVALID_NUMBER;  -- raise predefined exception
   END IF;
EXCEPTION
   WHEN INVALID_NUMBER THEN
      dbms_output.put_line('Handling invalid input by rolling back.');
      ROLLBACK;
END;
/

How PL/SQL Exceptions Propagate

When an exception is raised, if PL/SQL cannot find a handler for it in the current block or subprogram, the exception propagates. That is, the exception reproduces itself in successive enclosing blocks until a handler is found or there are no more blocks to search. If no handler is found, PL/SQL returns an unhandled exception error to the host environment.

Exceptions cannot propagate across remote procedure calls done through database links. A PL/SQL block cannot catch an exception raised by a remote subprogram. For a workaround, see «Defining Your Own Error Messages: Procedure RAISE_APPLICATION_ERROR».

Figure 10-1, Figure 10-2, and Figure 10-3 illustrate the basic propagation rules.

An exception can propagate beyond its scope, that is, beyond the block in which it was declared. Consider the following example:

BEGIN
   DECLARE  ---------- sub-block begins
     past_due EXCEPTION;
     due_date DATE := trunc(SYSDATE) - 1;
     todays_date DATE := trunc(SYSDATE);
   BEGIN
     IF due_date < todays_date THEN
        RAISE past_due;
     END IF;
   END;  ------------- sub-block ends
EXCEPTION
   WHEN OTHERS THEN
      ROLLBACK;
END;
/

Because the block that declares the exception past_due has no handler for it, the exception propagates to the enclosing block. But the enclosing block cannot reference the name PAST_DUE, because the scope where it was declared no longer exists. Once the exception name is lost, only an OTHERS handler can catch the exception. If there is no handler for a user-defined exception, the calling application gets this error:

ORA-06510: PL/SQL: unhandled user-defined exception

Reraising a PL/SQL Exception

Sometimes, you want to reraise an exception, that is, handle it locally, then pass it to an enclosing block. For example, you might want to roll back a transaction in the current block, then log the error in an enclosing block.

To reraise an exception, use a RAISE statement without an exception name, which is allowed only in an exception handler:

DECLARE
   salary_too_high  EXCEPTION;
   current_salary NUMBER := 20000;
   max_salary NUMBER := 10000;
   erroneous_salary NUMBER;
BEGIN
   BEGIN  ---------- sub-block begins
      IF current_salary > max_salary THEN
         RAISE salary_too_high;  -- raise the exception
      END IF;
   EXCEPTION
      WHEN salary_too_high THEN
         -- first step in handling the error
        dbms_output.put_line('Salary ' || erroneous_salary ||
          ' is out of range.');
        dbms_output.put_line('Maximum salary is ' || max_salary || '.');
         RAISE;  -- reraise the current exception
   END;  ------------ sub-block ends
EXCEPTION
   WHEN salary_too_high THEN
      -- handle the error more thoroughly
      erroneous_salary := current_salary;
      current_salary := max_salary;
     dbms_output.put_line('Revising salary from ' || erroneous_salary ||
       'to ' || current_salary || '.');
END;
/

Handling Raised PL/SQL Exceptions

When an exception is raised, normal execution of your PL/SQL block or subprogram stops and control transfers to its exception-handling part, which is formatted as follows:

EXCEPTION
   WHEN exception_name1 THEN  -- handler
      sequence_of_statements1
   WHEN exception_name2 THEN  -- another handler
      sequence_of_statements2
   ...
   WHEN OTHERS THEN           -- optional handler
      sequence_of_statements3
END;

To catch raised exceptions, you write exception handlers. Each handler consists of a WHEN clause, which specifies an exception, followed by a sequence of statements to be executed when that exception is raised. These statements complete execution of the block or subprogram; control does not return to where the exception was raised. In other words, you cannot resume processing where you left off.

The optional OTHERS exception handler, which is always the last handler in a block or subprogram, acts as the handler for all exceptions not named specifically. Thus, a block or subprogram can have only one OTHERS handler.

As the following example shows, use of the OTHERS handler guarantees that no exception will go unhandled:

EXCEPTION
   WHEN ... THEN
      -- handle the error
   WHEN ... THEN
      -- handle the error
   WHEN OTHERS THEN
      -- handle all other errors
END;

If you want two or more exceptions to execute the same sequence of statements, list the exception names in the WHEN clause, separating them by the keyword OR, as follows:

EXCEPTION
   WHEN over_limit OR under_limit OR VALUE_ERROR THEN
      -- handle the error

If any of the exceptions in the list is raised, the associated sequence of statements is executed. The keyword OTHERS cannot appear in the list of exception names; it must appear by itself. You can have any number of exception handlers, and each handler can associate a list of exceptions with a sequence of statements. However, an exception name can appear only once in the exception-handling part of a PL/SQL block or subprogram.

The usual scoping rules for PL/SQL variables apply, so you can reference local and global variables in an exception handler. However, when an exception is raised inside a cursor FOR loop, the cursor is closed implicitly before the handler is invoked. Therefore, the values of explicit cursor attributes are not available in the handler.

Handling Exceptions Raised in Declarations

Exceptions can be raised in declarations by faulty initialization expressions. For example, the following declaration raises an exception because the constant credit_limit cannot store numbers larger than 999:

DECLARE
   credit_limit CONSTANT NUMBER(3) := 5000;  -- raises an exception
BEGIN
   NULL;
EXCEPTION
   WHEN OTHERS THEN
      -- Cannot catch the exception. This handler is never called.
      dbms_output.put_line('Can''t handle an exception in a declaration.');
END;
/

Handlers in the current block cannot catch the raised exception because an exception raised in a declaration propagates immediately to the enclosing block.

Handling Exceptions Raised in Handlers

When an exception occurs within an exception handler, that same handler cannot catch the exception. An exception raised inside a handler propagates immediately to the enclosing block, which is searched to find a handler for this new exception. From there on, the exception propagates normally. For example:

EXCEPTION
   WHEN INVALID_NUMBER THEN
      INSERT INTO ...  -- might raise DUP_VAL_ON_INDEX
   WHEN DUP_VAL_ON_INDEX THEN ...  -- cannot catch the exception
END;

Branching to or from an Exception Handler

A GOTO statement can branch from an exception handler into an enclosing block.

A GOTO statement cannot branch into an exception handler, or from an exception handler into the current block.

Retrieving the Error Code and Error Message: SQLCODE and SQLERRM

In an exception handler, you can use the built-in functions SQLCODE and SQLERRM to find out which error occurred and to get the associated error message. For internal exceptions, SQLCODE returns the number of the Oracle error. The number that SQLCODE returns is negative unless the Oracle error is no data found, in which case SQLCODE returns +100. SQLERRM returns the corresponding error message. The message begins with the Oracle error code.

For user-defined exceptions, SQLCODE returns +1 and SQLERRM returns the message: User-Defined Exception.

unless you used the pragma EXCEPTION_INIT to associate the exception name with an Oracle error number, in which case SQLCODE returns that error number and SQLERRM returns the corresponding error message. The maximum length of an Oracle error message is 512 characters including the error code, nested messages, and message inserts such as table and column names.

If no exception has been raised, SQLCODE returns zero and SQLERRM returns the message: ORA-0000: normal, successful completion.

You can pass an error number to SQLERRM, in which case SQLERRM returns the message associated with that error number. Make sure you pass negative error numbers to SQLERRM.

Passing a positive number to SQLERRM always returns the message user-defined exception unless you pass +100, in which case SQLERRM returns the message no data found. Passing a zero to SQLERRM always returns the message normal, successful completion.

You cannot use SQLCODE or SQLERRM directly in a SQL statement. Instead, you must assign their values to local variables, then use the variables in the SQL statement, as shown in the following example:

DECLARE
   err_msg VARCHAR2(100);
BEGIN
   /* Get a few Oracle error messages. */
   FOR err_num IN 1..3 LOOP
     err_msg := SUBSTR(SQLERRM(-err_num),1,100);
     dbms_output.put_line('Error number = ' || err_num);
     dbms_output.put_line('Error message = ' || err_msg);
   END LOOP;
END;
/

The string function SUBSTR ensures that a VALUE_ERROR exception (for truncation) is not raised when you assign the value of SQLERRM to err_msg. The functions SQLCODE and SQLERRM are especially useful in the OTHERS exception handler because they tell you which internal exception was raised.

Note: When using pragma RESTRICT_REFERENCES to assert the purity of a stored function, you cannot specify the constraints WNPS and RNPS if the function calls SQLCODE or SQLERRM.

Catching Unhandled Exceptions

Remember, if it cannot find a handler for a raised exception, PL/SQL returns an unhandled exception error to the host environment, which determines the outcome. For example, in the Oracle Precompilers environment, any database changes made by a failed SQL statement or PL/SQL block are rolled back.

Unhandled exceptions can also affect subprograms. If you exit a subprogram successfully, PL/SQL assigns values to OUT parameters. However, if you exit with an unhandled exception, PL/SQL does not assign values to OUT parameters (unless they are NOCOPY parameters). Also, if a stored subprogram fails with an unhandled exception, PL/SQL does not roll back database work done by the subprogram.

You can avoid unhandled exceptions by coding an OTHERS handler at the topmost level of every PL/SQL program.

Tips for Handling PL/SQL Errors

In this section, you learn three techniques that increase flexibility.

Continuing after an Exception Is Raised

An exception handler lets you recover from an otherwise fatal error before exiting a block. But when the handler completes, the block is terminated. You cannot return to the current block from an exception handler. In the following example, if the SELECT INTO statement raises ZERO_DIVIDE, you cannot resume with the INSERT statement:

DECLARE
   pe_ratio NUMBER(3,1);
BEGIN
   DELETE FROM stats WHERE symbol = 'XYZ';
   SELECT price / NVL(earnings, 0) INTO pe_ratio FROM stocks
      WHERE symbol = 'XYZ';
   INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio);
EXCEPTION
   WHEN ZERO_DIVIDE THEN
      NULL;
END;
/

You can still handle an exception for a statement, then continue with the next statement. Place the statement in its own sub-block with its own exception handlers. If an error occurs in the sub-block, a local handler can catch the exception. When the sub-block ends, the enclosing block continues to execute at the point where the sub-block ends. Consider the following example:

DECLARE
   pe_ratio NUMBER(3,1);
BEGIN
   DELETE FROM stats WHERE symbol = 'XYZ';
   BEGIN  ---------- sub-block begins
      SELECT price / NVL(earnings, 0) INTO pe_ratio FROM stocks
         WHERE symbol = 'XYZ';
   EXCEPTION
      WHEN ZERO_DIVIDE THEN
         pe_ratio := 0;
   END;  ---------- sub-block ends
   INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio);
EXCEPTION
   WHEN OTHERS THEN
      NULL;
END;
/

In this example, if the SELECT INTO statement raises a ZERO_DIVIDE exception, the local handler catches it and sets pe_ratio to zero. Execution of the handler is complete, so the sub-block terminates, and execution continues with the INSERT statement.

You can also perform a sequence of DML operations where some might fail, and process the exceptions only after the entire operation is complete, as described in «Handling FORALL Exceptions with the %BULK_EXCEPTIONS Attribute».

Retrying a Transaction

After an exception is raised, rather than abandon your transaction, you might want to retry it. The technique is:

  1. Encase the transaction in a sub-block.

  2. Place the sub-block inside a loop that repeats the transaction.

  3. Before starting the transaction, mark a savepoint. If the transaction succeeds, commit, then exit from the loop. If the transaction fails, control transfers to the exception handler, where you roll back to the savepoint undoing any changes, then try to fix the problem.

In the following example, the INSERT statement might raise an exception because of a duplicate value in a unique column. In that case, we change the value that needs to be unique and continue with the next loop iteration. If the INSERT succeeds, we exit from the loop immediately. With this technique, you should use a FOR or WHILE loop to limit the number of attempts.

DECLARE
   name   VARCHAR2(20);
   ans1   VARCHAR2(3);
   ans2   VARCHAR2(3);
   ans3   VARCHAR2(3);
   suffix NUMBER := 1;
BEGIN
   FOR i IN 1..10 LOOP  -- try 10 times
      BEGIN  -- sub-block begins
         SAVEPOINT start_transaction;  -- mark a savepoint
         /* Remove rows from a table of survey results. */
         DELETE FROM results WHERE answer1 = 'NO';
         /* Add a survey respondent's name and answers. */
         INSERT INTO results VALUES (name, ans1, ans2, ans3);
 -- raises DUP_VAL_ON_INDEX if two respondents have the same name
         COMMIT;
         EXIT;
      EXCEPTION
         WHEN DUP_VAL_ON_INDEX THEN
            ROLLBACK TO start_transaction;  -- undo changes
            suffix := suffix + 1;           -- try to fix problem
            name := name || TO_CHAR(suffix);
      END;  -- sub-block ends
   END LOOP;
END;
/

Using Locator Variables to Identify Exception Locations

Using one exception handler for a sequence of statements, such as INSERT, DELETE, or UPDATE statements, can mask the statement that caused an error. If you need to know which statement failed, you can use a locator variable:

DECLARE
   stmt INTEGER;
   name VARCHAR2(100);
BEGIN
   stmt := 1;  -- designates 1st SELECT statement
   SELECT table_name INTO name FROM user_tables WHERE table_name LIKE 'ABC%';
   stmt := 2;  -- designates 2nd SELECT statement
   SELECT table_name INTO name FROM user_tables WHERE table_name LIKE 'XYZ%';
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      dbms_output.put_line('Table name not found in query ' || stmt);
END;
/

Overview of PL/SQL Compile-Time Warnings

To make your programs more robust and avoid problems at run time, you can turn on checking for certain warning conditions. These conditions are not serious enough to produce an error and keep you from compiling a subprogram. They might point out something in the subprogram that produces an undefined result or might create a performance problem.

To work with PL/SQL warning messages, you use the PLSQL_WARNINGS initialization parameter, the DBMS_WARNING package, and the USER/DBA/ALL_PLSQL_OBJECT_SETTINGS views.

PL/SQL Warning Categories

PL/SQL warning messages are divided into categories, so that you can suppress or display groups of similar warnings during compilation. The categories are:

Severe: Messages for conditions that might cause unexpected behavior or wrong results, such as aliasing problems with parameters.

Performance: Messages for conditions that might cause performance problems, such as passing a VARCHAR2 value to a NUMBER column in an INSERT statement.

Informational: Messages for conditions that do not have an effect on performance or correctness, but that you might want to change to make the code more maintainable, such as dead code that can never be executed.

The keyword All is a shorthand way to refer to all warning messages.

You can also treat particular messages as errors instead of warnings. For example, if you know that the warning message PLW-05003 represents a serious problem in your code, including 'ERROR:05003' in the PLSQL_WARNINGS setting makes that condition trigger an error message (PLS_05003) instead of a warning message. An error message causes the compilation to fail.

Controlling PL/SQL Warning Messages

To let the database issue warning messages during PL/SQL compilation, you set the initialization parameter PLSQL_WARNINGS. You can enable and disable entire categories of warnings (ALL, SEVERE, INFORMATIONAL, PERFORMANCE), enable and disable specific message numbers, and make the database treat certain warnings as compilation errors so that those conditions must be corrected.

This parameter can be set at the system level or the session level. You can also set it for a single compilation by including it as part of the ALTER PROCEDURE statement. You might turn on all warnings during development, turn off all warnings when deploying for production, or turn on some warnings when working on a particular subprogram where you are concerned with some aspect, such as unnecessary code or performance.

ALTER SYSTEM SET PLSQL_WARNINGS='ENABLE:ALL'; -- For debugging during development.
ALTER SESSION SET PLSQL_WARNINGS='ENABLE:PERFORMANCE'; -- To focus on one aspect.
ALTER PROCEDURE hello COMPILE PLSQL_WARNINGS='ENABLE:PERFORMANCE'; -- Recompile with extra checking.
ALTER SESSION SET PLSQL_WARNINGS='DISABLE:ALL'; -- To turn off all warnings.
-- We want to hear about 'severe' warnings, don't want to hear about 'performance'
-- warnings, and want PLW-06002 warnings to produce errors that halt compilation.
ALTER SESSION SET PLSQL_WARNINGS='ENABLE:SEVERE','DISABLE:PERFORMANCE','ERROR:06002';

Warning messages can be issued during compilation of PL/SQL subprograms; anonymous blocks do not produce any warnings.

The settings for the PLSQL_WARNINGS parameter are stored along with each compiled subprogram. If you recompile the subprogram with a CREATE OR REPLACE statement, the current settings for that session are used. If you recompile the subprogram with an ALTER ... COMPILE statement, the current session setting might be used, or the original setting that was stored with the subprogram, depending on whether you include the REUSE SETTINGS clause in the statement.

To see any warnings generated during compilation, you use the SQL*Plus SHOW ERRORS command or query the USER_ERRORS data dictionary view. PL/SQL warning messages all use the prefix PLW.

Using the DBMS_WARNING Package

If you are writing a development environment that compiles PL/SQL subprograms, you can control PL/SQL warning messages by calling subprograms in the DBMS_WARNING package. You might also use this package when compiling a complex application, made up of several nested SQL*Plus scripts, where different warning settings apply to different subprograms. You can save the current state of the PLSQL_WARNINGS parameter with one call to the package, change the parameter to compile a particular set of subprograms, then restore the original parameter value.

For example, here is a procedure with unnecessary code that could be removed. It could represent a mistake, or it could be intentionally hidden by a debug flag, so you might or might not want a warning message for it.

CREATE OR REPLACE PROCEDURE dead_code
AS
  x number := 10;
BEGIN
  if x = 10 then
      x := 20;
  else
    x := 100; -- dead code (never reached)
  end if;
END dead_code;/
-- By default, the preceding procedure compiles with no errors or warnings.

-- Now enable all warning messages, just for this session.
CALL DBMS_WARNING.SET_WARNING_SETTING_STRING('ENABLE:ALL' ,'SESSION');

-- Check the current warning setting.
select dbms_warning.get_warning_setting_string() from dual;

-- When we recompile the procedure, we will see a warning about the dead code.
ALTER PROCEDURE dead_code COMPILE;

See Also: ALTER PROCEDURE, DBMS_WARNING package in the PL/SQL Packages and Types Reference, PLW- messages in the Oracle Database Error Messages

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ora 12705 cannot access nls data files or invalid environment specified ошибка
  • Ora 12638 credential retrieval failed ошибка