Pl sql numeric or value error character to number conversion error перевод

How to Resolve ORA-06502: PL/SQL: numeric or value error: character to number conversion error ORA-06502 ORA-06502 means that PL/SQL engine cannot convert a character-typed string into a number or a subset of arithmetic for overall evaluation. Mostly, it’s because of the following problems: Numeric Type Conversion Numeric Operator Precedence A. Numeric Type Conversion ORA-06502 […]
Я реализовал это так

Код:
exception when others then

Но выдаётся не такое сообщение, как в вызываемой в фоновом режиме операции.
ORA-06502: PL/SQL: numeric or value error: character to number conversion error

Т.е. не корректное для пользователя? как в операции
«Нельзя закрыть договор. «

Подскажите,где ошибся?

Налицо ошибка преобразования. Какой-то символ затисался в строку, которую вы явно или неявно преобразовываете в number. format_error_backtrace даст ответ, где именно идет преобразование.

Источник

ORA-6502: ORA-06502: PL/SQL: numeric or value error: character to number conversion error

Good Afternoon Community,

I’m Using Oracle DB 12c

I’m trying to use To_Char to Convert Number to Char to add Formatting But I Can Not

Figure out Character to Number Conversion Error on Line 24 Commented and Highlighted in Red Below

ORA-06502: PL/SQL: numeric or value error: character to number conversion error

ORA-06512: at line 24

06502. 00000 — «PL/SQL: numeric or value error%s»

*Cause: An arithmetic, numeric, string, conversion, or constraint error

occurred. For example, this error occurs if an attempt is made to

assign the value NULL to a variable declared NOT NULL, or if an

attempt is made to assign an integer larger than 99 to a variable

*Action: Change the data, how it is manipulated, or how it is declared so

that values do not violate constraints.

v_P10_RECPT_NMBR1 VARCHAR2(25) := ‘9000000294’;

v_P10_RECPT_NMBR2 VARCHAR2(25) := ‘9000000059’;

v_P10_SubTotal Number(11,2) := 3111.59;

v_SubTotal_Error char(1) := ‘T’;

select Abs(Nvl(Sum(subtotal),0)) into v_subtotal

where refunded_recpt_nmbr = v_P10_RECPT_NMBR1;

select Abs(nvl(subtotal,0)) into v_original_subtotal

where receiptnumber = v_P10_RECPT_NMBR2;

—CHECK FOR POSITIVE NUMBERS — REFUNDS HAVE TO BE ENTERED WITH NEGATIVE AMOUNT—-P10_SUBTOTAL,’,’,’,») > 0

IF TO_CHAR(v_P10_SubTotal, ‘99,999.99’) > ‘0’

THEN v_SubTotal_Error := ‘X’;

—check for excessive refund amounts

———-Error Lies here on Line 24 ((ABS(To_Char(v_P10_SubTotal,’99,999.99′)) + to_char(v_subtotal,’99,999.99′)) > to_char(v_original_subtotal, ‘99,999.99’))

Источник

ORA-6502: ORA-06502: PL/SQL: numeric or value error: character to number conversion error

Good Afternoon Community,

I’m Using Oracle DB 12c

I’m trying to use To_Char to Convert Number to Char to add Formatting But I Can Not

Figure out Character to Number Conversion Error on Line 24 Commented and Highlighted in Red Below

ORA-06502: PL/SQL: numeric or value error: character to number conversion error

ORA-06512: at line 24

06502. 00000 — «PL/SQL: numeric or value error%s»

*Cause: An arithmetic, numeric, string, conversion, or constraint error

occurred. For example, this error occurs if an attempt is made to

assign the value NULL to a variable declared NOT NULL, or if an

attempt is made to assign an integer larger than 99 to a variable

*Action: Change the data, how it is manipulated, or how it is declared so

that values do not violate constraints.

v_P10_RECPT_NMBR1 VARCHAR2(25) := ‘9000000294’;

v_P10_RECPT_NMBR2 VARCHAR2(25) := ‘9000000059’;

v_P10_SubTotal Number(11,2) := 3111.59;

v_SubTotal_Error char(1) := ‘T’;

select Abs(Nvl(Sum(subtotal),0)) into v_subtotal

where refunded_recpt_nmbr = v_P10_RECPT_NMBR1;

select Abs(nvl(subtotal,0)) into v_original_subtotal

where receiptnumber = v_P10_RECPT_NMBR2;

—CHECK FOR POSITIVE NUMBERS — REFUNDS HAVE TO BE ENTERED WITH NEGATIVE AMOUNT—-P10_SUBTOTAL,’,’,’,») > 0

IF TO_CHAR(v_P10_SubTotal, ‘99,999.99’) > ‘0’

THEN v_SubTotal_Error := ‘X’;

—check for excessive refund amounts

———-Error Lies here on Line 24 ((ABS(To_Char(v_P10_SubTotal,’99,999.99′)) + to_char(v_subtotal,’99,999.99′)) > to_char(v_original_subtotal, ‘99,999.99’))

Источник

Pl sql numeric or value error character to number conversion error перевод

В чем может быть причина такой ошибки?

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

И где можно увеличить этот character string buffer?


Sergey13 © ( 2006-11-13 13:10 ) [1]

ORA-06502 PL/SQL: numeric or value errorstring

An arithmetic, numeric, string, conversion, or constraint error occurred. For example, this error occurs if an attempt is made to assign the value NULL to a variable declared NOT NULL, or if an attempt is made to assign an integer larger than 99 to a variable declared NUMBER(2).

Change the data, how it is manipulated, or how it is declared so that values do not violate constraints.


Desdechado © ( 2006-11-13 13:14 ) [2]


SergP © ( 2006-11-13 13:27 ) [3]

Понял.
Теперь как бы найти в каком месте это происходит, а то процедура большая, а в логе выводится только номер строки где raise стоит.


Sergey13 © ( 2006-11-13 13:30 ) [4]

> [3] SergP © (13.11.06 13:27)

В PL/SQL Developere например есть отладчик процедур.

смысл такого
EXCEPTION
WHEN OTHERS
THEN
RAISE;
END;
обработчика?
без него тебе бы и строку показало


ANB © ( 2006-11-13 13:34 ) [6]


> SergP © (13.11.06 13:27) [3]

Хех. Известный косяк. Сохраняй на всех перехватах исключений ее трассировку. так сможешь найти место ошибки. И сделай все варчаровые переменные подлиннее. Оракл сильно от этого не напряжется. Кстати, возможный вариант, из-за чего может появится ошибка :
имеем S varchar2(10). S := «Вася123456»; На 10-ке (XE) вполне вероятна ошибка невлезания, т.к. русские буквы занимают по 2 байта. Лечится заменой varchar2(10) на varchar2(10 char)


SergP © ( 2006-11-13 13:49 ) [7]

Спасибо. Убрал этот обработчик и нашел где.


Desdechado © ( 2006-11-13 13:52 ) [8]

> русские буквы занимают по 2 байта
Это если NVARCHAR2 пытаться туда запихнуть. Или нет?


SergP © ( 2006-11-13 14:01 ) [9]

> [8] Desdechado © (13.11.06 13:52)
> > русские буквы занимают по 2 байта
> Это если NVARCHAR2 пытаться туда запихнуть. Или нет?

там оказалось что не с русскими буквами связано, а с цифрами.
видимо число не влазило в

v_n_reg_sa VARCHAR2 (20) := NULL;

увеличил на глаз до 24. Теперь работает.


> Это если NVARCHAR2 пытаться туда запихнуть. Или нет?

Не. Просто константу. Причем на 9-ке с этим проблем не было.


SergP © ( 2006-11-13 15:24 ) [11]

> [9] SergP © (13.11.06 14:01)
>
> увеличил на глаз до 24. Теперь работает.

Блин. Разработчики редиски. Сегодня прислали версию, вместо той что раньше прислали. Посмотрел, а они там уже сами увеличили размеры переменных. А я часа 1,5-2 потратил на поиск этих «багов».


Desdechado © ( 2006-11-13 16:09 ) [12]

разработчиков [5] — строем за метлами

> Не. Просто константу. Причем на 9-ке с этим проблем не было.
В какой кодировке создавалась БД? В какой кодировке схема? Может, умолчания изменились?


k2 © ( 2006-11-13 16:12 ) [13]

Desdechado © (13.11.06 16:09) [12]
для nls_length_semantics умолчание изменилось вроде:
в 9-ке-char, в 10-ке-byte


ANB © ( 2006-11-13 16:13 ) [14]


> Desdechado © (13.11.06 16:09) [12]

ЭЭЭЭ. Просто пнули XE она сама все поставила. Не задавая лишних вопросов. Хотя, в принципе, указание размерности никому не мешает, зато код будет работать при любой настройке базы.


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

А вот гады пишут, что лучше nls_length_semantics устанавливать, а саму семантику в объявлениях только при крайней нужде менять. Оно говорят портабельнее получается. Домены бы в Оракл — цены б ему не было.


Desdechado © ( 2006-11-13 16:32 ) [16]

Да, доменов мне не хватает.

k2 © (13.11.06 16:12) [13]
На своей 9-ке проверил (умолчания не трогали) — BYTE. И на линухе, и на выни.


k2 © ( 2006-11-13 16:35 ) [17]

Desdechado © (13.11.06 16:32) [16]
знач наврала сорри, у меня это запросто 🙂


ANB © ( 2006-11-13 16:43 ) [18]


> Desdechado © (13.11.06 16:32) [16]

Не, это из-за кодировки. Почему то в XE по дефолту полуторнобайтовая кодировка врублена (не помню как она называется, однако dump хорошо это показывает).


Игорь Шевченко © ( 2006-11-13 17:21 ) [19]

ANB © (13.11.06 16:43) [18]


> Почему то в XE по дефолту полуторнобайтовая кодировка врублена

А это я вполне могу вечером посмотреть, стоит XE с кодировкой по умолчанию. XE юникодный (XEUniv)


Игорь Шевченко © ( 2006-11-13 22:55 ) [20]

В XE без всяких исправлений, как было, так и встало.

NLS_TIME_FORMAT HH.MI.SSXFF AM

NLS_TIMESTAMP_FORMAT DD-MON-RR HH.MI.SSXFF AM

NLS_TIME_TZ_FORMAT HH.MI.SSXFF AM TZR

NLS_TIMESTAMP_TZ_FORMAT DD-MON-RR HH.MI.SSXFF AM TZR


ANB © ( 2006-11-14 10:37 ) [21]

NLS_CHARACTERSET AL32UTF8
NLS_LENGTH_SEMANTICS BYTE
NLS_NCHAR_CHARACTERSET AL16UTF16

Вот эти параметры намекают мне, что у тебя по идее должна быть такая же проблема, если явно не указать размерность char


Игорь Шевченко © ( 2006-11-14 11:09 ) [22]

ANB © (14.11.06 10:37) [21]


> Вот эти параметры намекают мне, что у тебя по идее должна
> быть такая же проблема, если явно не указать размерность
> char

Безусловно. Я указываю char в объявлении полей, когда допускаю, что в полях будут находиться символы, отличные от #0-#127, а гады говорят, что надо устанавливать nls_length_semantics для базы, а в объявлениях ничего не трогать.


ANB © ( 2006-11-14 11:18 ) [23]


> Игорь Шевченко © (14.11.06 11:09) [22]

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


ANB © ( 2006-11-14 11:19 ) [24]


> а гады говорят, что надо устанавливать nls_length_semantics
> для базы

А где ты это накопал ?


Игорь Шевченко © ( 2006-11-14 11:45 ) [25]

ANB © (14.11.06 11:18) [23]


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

А если бы лимит в Оракле был на 30000 байт ? 🙂

«The BYTE and CHAR qualifiers override the semantics specified by the NLS_LENGTH_SEMANTICS parameter, which has a default of byte semantics. For performance reasons, Oracle recommends that you use the NLS_LENGTH_SEMANTICS parameter to set length semantics and that you use the BYTE and CHAR qualifiers only when necessary to override the parameter«

«Oracle® Database SQL Reference
10g Release 1 (10.1)
Part Number B10759-01″


ANB © ( 2006-11-14 11:57 ) [26]


> А если бы лимит в Оракле был на 30000 байт ? 🙂

Ну и сделал бы столько 🙂 На размер БД это не влияет. Они же варчаровые.

Спасибо за ссылку.


Игорь Шевченко © ( 2006-11-14 12:16 ) [27]


> Ну и сделал бы столько 🙂 На размер БД это не влияет. Они
> же варчаровые.

Наверное ты Celko не читал. А зря, он как раз очень аргументированно возражает против такого бездумного назначения максимального размера полям.
Рекомендую: http://www.mini-mag.ru/?cid=2170&tov=163372


ANB © ( 2006-11-14 12:20 ) [28]


> Рекомендую: http://www.mini-mag.ru/?cid=2170&tov=163372

Тьфу, млин. Это ссылка на магазин.
Звиняйте — у меня свой авторитет есть 🙂 Тем более он рулил проектом и я у него и спросил — делать так или не надо. Индексы составные поругались поначалу, он размер блока побольше сделал — и всех делов 🙂


k2 © ( 2006-11-14 12:24 ) [29]

и мы даже знаем кто 🙂
только Селко наверное тож пару раз проектами рулил 🙂


Игорь Шевченко © ( 2006-11-14 12:59 ) [30]

ANB © (14.11.06 12:20) [28]


> Звиняйте — у меня свой авторитет есть 🙂 Тем более он рулил
> проектом и я у него и спросил — делать так или не надо.
>

Авторитет авторитету люпус эст.


> Индексы составные поругались поначалу, он размер блока побольше
> сделал — и всех делов 🙂

Особенно в SQL*Plus удобно запросы с такими полями делать.


ANB © ( 2006-11-14 13:04 ) [31]


> Особенно в SQL*Plus удобно запросы с такими полями делать.
> ..

Я тоадом пользуюсь. он под ширину данных ширину колонки подгоняет


Игорь Шевченко © ( 2006-11-14 13:12 ) [32]

ANB © (14.11.06 13:04) [31]


> Я тоадом пользуюсь. он под ширину данных ширину колонки
> подгоняет

если там пара сотен тысяч записей.

Кроме того, извини, когда жаба будет поставляться в дистрибутиве оракла, тогда имеет смысл говорить, что ты ей пользуешься и всем рекомендуешь. Тора, она хоть бесплатная, но тормозная, а жаба денег стоит и потому давит.
Вот и остается SQL*Plus


ANB © ( 2006-11-14 15:48 ) [33]


> Вот и остается SQL*Plus

Есть еще pl/sql девелопер, склнафигатор (жуткая гадость).
А разве жаба платная ?


Игорь Шевченко © ( 2006-11-14 16:18 ) [34]

ANB © (14.11.06 15:48) [33]


> А разве жаба платная ?

Вообще-то да. Как и PL/SQL Developer.

Про жабу интересно написано:
«The Toad Freeware version may be used for a maximum of five (5) users within Licensee»s organization and expires each sixty (60) days, after which you will need to download and install the product again»
http://www.toadsoft.com/lic_agree.html

Насколько я знаю, бесплатная TORA ну и SQL*Plus 🙂


k2 © ( 2006-11-14 16:40 ) [35]

ANB © (14.11.06 13:04) [31]
Андрей, а твоя жаба оракловые пакеты понимает на десятке? и какая тогда версия?


Val © ( 2006-11-14 17:02 ) [36]

>[15] Игорь Шевченко © (13.11.06 16:26)
>..Домены бы в Оракл — цены б ему не было.
да вроде %TYPE неплохо справляется.


ANB © ( 2006-11-14 17:08 ) [37]


> Вообще-то да. Как и PL/SQL Developer.

Млин. А я и не знал. Фришную версию не ставлю — она кривая. А так у меня ключ есть. Пока подходит.


> Андрей, а твоя жаба оракловые пакеты понимает на десятке?
> и какая тогда версия?

Старая жаба вообще отказалась работать с 10-кой. Ща у меня 8-я версия. Вроде проблем нету особых. Нарывался на глюк в 9-ке — здоровые пакеты с отладкой не хотели компиляться. Пришлось их девелопером компилять.


k2 © ( 2006-11-14 17:20 ) [38]

у меня 8.0.0.47 категорически отказывается просматривать в 10-ке процедуры , функции и спецификацию пакета, хотя боди и просматривает и редактировать и компилить пожалуйста, такая загогулина :-/


ANB © ( 2006-11-14 17:30 ) [39]


> k2 © (14.11.06 17:20) [38]

Упс. И у меня такой же. Хотя я на живой 10-ке его не гонял — только на XE. Свежее версии нету ? Вполне возможно, что в этой не выгребли все баги. Таки 7-ка вообще не умела работать с ораклом 10, даже XE.


k2 © ( 2006-11-14 17:36 ) [40]

у меня 10.2.0.2
кстати если прихъодилось жабу под mssql-ем гонять пристойно себя ведет?


Игорь Шевченко © ( 2006-11-14 17:42 ) [41]

k2 © (14.11.06 17:20) [38]
ANB © (14.11.06 17:30) [39]

Кстати фриварная только что скачаная жаба (8.5.0.50g) точно так же не умеет с десяткой работать на предмет процедур/пакетов.
Что интересно — ТОРА умеет. Но Тора глючная и тормозная.

Val © (14.11.06 17:02) [36]


> да вроде %TYPE неплохо справляется.

В какое место в объявлении поля в таблице вставлять %TYPE ?


k2 © ( 2006-11-14 17:57 ) [42]

Игорь Шевченко © (14.11.06 17:42) [41]
Oracle Developer немножко знает про домены, после генерации на базе это выглядит как табличка cg_ref_codes (сейчас нет дизайнера, не знаю настраивается) вида:
CREATE TABLE .CG_REF_CODES
(
RV_DOMAIN VARCHAR2(100) NOT NULL,
RV_LOW_VALUE VARCHAR2(240) NOT NULL,
RV_HIGH_VALUE VARCHAR2(240),
RV_ABBREVIATION VARCHAR2(240),
RV_MEANING VARCHAR2(240),
RV_TYPE VARCHAR2(10)
)
TABLESPACE USERS
LOGGING
NOCACHE
NOPARALLEL;
CREATE INDEX .X_CG_REF_CODES_1 ON .CG_REF_CODES
(RV_DOMAIN, RV_LOW_VALUE)
LOGGING
TABLESPACE
NOPARALLEL;
DROP SYNONYM SGDEVNU1.CG_REF_CODES;
CREATE SYNONYM SGDEVNU1.CG_REF_CODES FOR .CG_REF_CODES;
ALTER TABLE .CG_REF_CODES ADD (
CONSTRAINT RV_PK PRIMARY KEY (RV_DOMAIN, RV_LOW_VALUE));
если это те домены и ничего не попутала 🙂


Val © ( 2006-11-14 17:57 ) [43]

>[41] Игорь Шевченко © (14.11.06 17:42)
зачем?


Игорь Шевченко © ( 2006-11-14 18:03 ) [44]

Val © (14.11.06 17:57) [43]

Ну чтобы домен был.

Оно ж как мыслится:

CREATE DOMAIN DFOO CHAR(3) DEFAULT «BAR» NOT NULL
CHECK (DFOO IN («BAR», «BAZ», «BOO»));

а в объявлении таблицы пишешь просто
CREATE TABLE FOOTABLE (
.
FOO DFOO,
.
);


Игорь Шевченко © ( 2006-11-14 18:04 ) [45]

k2 © (14.11.06 17:57) [42]

То ж небось для самого дизайнера.


Val © ( 2006-11-14 18:06 ) [46]

>[42] k2 © (14.11.06 17:57)
Здесь под доменом понимается определенный пользователем тип, который может быть и типом поля таблицы. Такого в Оракле пока я не встретил.


Val © ( 2006-11-14 18:22 ) [47]

>[44] Игорь Шевченко © (14.11.06 18:03)
Ну не знаю. Дело привычки. В ИБ привык, в Оракле затем отвык — оказалось не так уж и нужно мне это в таблицах.


ANB © ( 2006-11-14 18:48 ) [48]


> Игорь Шевченко © (14.11.06 18:04) [45]

Не. Как то же оракл разрешает создавать поля с объектными типами. Надо просто покопаться.
Хотя впрямую — да, обломс.


Val © ( 2006-11-14 19:02 ) [49]

>ANB © (14.11.06 18:48)
поля с объектыми типами? может, таблицы объектного типа?


Desdechado © ( 2006-11-14 19:09 ) [50]

Val © (14.11.06 19:02) [49]
и поля объектных типов тоже


Val © ( 2006-11-14 19:17 ) [51]

>[50] Desdechado © (14.11.06 19:09)
речь о вложенных таблицах?


Desdechado © ( 2006-11-14 20:41 ) [52]

Val © (14.11.06 19:17) [51]
нет, например:
CREATE TABLE TUNE(
REGION_ID NUMBER(10) NOT NULL,
SDO_MIN_RECT MDSYS.SDO_GEOMETRY,
SDO_DIMINFO MDSYS.SDO_DIM_ARRAY
);


Игорь Шевченко © ( 2006-11-15 10:27 ) [53]

Val © (14.11.06 18:22) [47]


> Ну не знаю. Дело привычки. В ИБ привык, в Оракле затем
> отвык — оказалось не так уж и нужно мне это в таблицах.

Мне просто лень писать каждый раз одни и те же проверки. И лень потом исправлять во многих местах, если DOMAIN изменился по какой-то причине.


Val © ( 2006-11-15 14:24 ) [54]

>Desdechado © (14.11.06 20:41)
MDSYS.SDO_GEOMETRY
и
MDSYS.SDO_DIM_ARRAY
не являются таблицами по сути?

>[53] Игорь Шевченко © (15.11.06 10:27)
С этим я согласен(не зря же домены придуманы), но есть другой нюанс — создавая ограничения руками — вы именуете их как нужно вам, всегда можете ими управлять для конкретной таблицы не трогая других и т.д. Просто разные подходы.

Источник

Adblock
detector

Are you getting an ORA-06502 error message when working with Oracle SQL? Learn how to resolve it and what causes it in this article.

ORA-06502 Cause

The cause of the “ORA-06502 PL/SQL numeric or value error” can be one of many things:

  1. A value is being assigned to a numeric variable, but the value is larger than what the variable can handle.
  2. A non-numeric value is being assigned to a numeric variable.
  3. A value of NULL is being assigned to a variable which has a NOT NULL constraint.

Let’s take a look at the solutions for each of these causes.

The solution for this error will depend on the cause.

Let’s see an example of each of the three causes mentioned above.

Solution 1: Value Larger than Variable (Number Precision Too Large)

In this example, we have some code that is setting a numeric variable to a value which is larger than what can be stored.

Let’s create this procedure which declares and then sets a variable:

CREATE OR REPLACE PROCEDURE TestLargeNumber
AS
  testNumber NUMBER(3);
BEGIN
  testNumber := 4321;
END;

If we compile it, it compiles with no errors.

Procedure TESTLARGENUMBER compiled

Now, let’s run the procedure.

EXEC TestLargeNumber;

We get an error:

Error starting at line : 8 in command -
EXEC TestLargeNumber
Error report -
ORA-06502: PL/SQL: numeric or value error: number precision too large
ORA-06512: at "SYSTEM.TESTLARGENUMBER", line 5
ORA-06512: at line 1
06502. 00000 -  "PL/SQL: numeric or value error%s"
*Cause:    An arithmetic, numeric, string, conversion, or constraint error
           occurred. For example, this error occurs if an attempt is made to
           assign the value NULL to a variable declared NOT NULL, or if an
           attempt is made to assign an integer larger than 99 to a variable
           declared NUMBER(2).
*Action:   Change the data, how it is manipulated, or how it is declared so
           that values do not violate constraints.

The error we’ve gotten is “ORA-06502: PL/SQL: numeric or value error: number precision too large”. It also includes an ORA-06512, but that error just mentions the next line the code is run from, as explained in this article on ORA-06512.

This is because our variable testNumber can only hold 3 digits, because it was declared as a NUMBER(3). But, the value we’re setting it to a few lines later is 4 digit long (4321).

So, the value is too large for the variable.

To resolve it, increase the size of your variable, or manipulate your value to fit the size of the variable (if possible).

In our example , we can change the size of the variable.

CREATE OR REPLACE PROCEDURE TestLargeNumber
AS
  testNumber NUMBER(4);
BEGIN
  testNumber := 4321;
END;
Procedure TESTLARGENUMBER compiled

Now, let’s run the procedure.

EXEC TestLargeNumber;
PL/SQL procedure successfully completed.

The procedure runs successfully. We don’t get any output (because we didn’t code any in), but there are no errors.

Read more on the Oracle data types here.

Solution 2: Non-Numeric Value

Another way to find and resolve this error is by ensuring you’re not setting a numeric variable to a non-numeric value.

For example, take a look at this function.

CREATE OR REPLACE PROCEDURE TestNonNumeric
AS
  testNumber NUMBER(4);
BEGIN
  testNumber := 'Yes';
END;
Procedure TESTNONNUMERIC compiled

The procedure compiles successfully. Now, let’s fun the function.

EXEC TestNonNumeric;
Error starting at line : 8 in command -
EXEC TestNonNumeric
Error report -
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at "SYSTEM.TESTNONNUMERIC", line 5
ORA-06512: at line 1
06502. 00000 -  "PL/SQL: numeric or value error%s"
*Cause:    An arithmetic, numeric, string, conversion, or constraint error
           occurred. For example, this error occurs if an attempt is made to
           assign the value NULL to a variable declared NOT NULL, or if an
           attempt is made to assign an integer larger than 99 to a variable
           declared NUMBER(2).
*Action:   Change the data, how it is manipulated, or how it is declared so
           that values do not violate constraints.

The error we get is “ORA-06502: PL/SQL: numeric or value error: character to number conversion error”.

This happens because our variable testNumber is set to a NUMBER, but a few lines later, we’re setting it to a string value which cannot be converted to a number

To resolve this error:

  1. Ensure the value coming in is a number and not a string.
  2. Convert your string to a number using TO_NUMBER (the conversion might happen implicitly but this may help).
  3. Convert your string to the ASCII code that represents the string using the ASCII function.
  4. Change the data type of your variable (but check that your code is getting the right value first).

The solution you use will depend on your requirements.

Solution 3: NOT NULL Variable

This error can appear if you try to set a NULL value to a NOT NULL variable.

Let’s take a look at this code here:

CREATE OR REPLACE PROCEDURE TestNonNull
AS
  testNumber NUMBER(4) NOT NULL := 10;
  nullValue NUMBER(4) := NULL;
BEGIN
  testNumber := nullValue;
END;

Procedure TESTNONNULL compiled

Now, the reason we’re using a variable to store NULL and not just setting testNumber to NULL is because we get a different error in that case. Besides, it’s probably more likely that your NULL value will come from another system or a database table, rather than a hard-coded NULL value.

Let’s run this function now.

Error starting at line : 9 in command -
EXEC TestNonNull
Error report -
ORA-06502: PL/SQL: numeric or value error
ORA-06512: at "SYSTEM.TESTNONNULL", line 6
ORA-06512: at line 1
06502. 00000 -  "PL/SQL: numeric or value error%s"
*Cause:    An arithmetic, numeric, string, conversion, or constraint error
           occurred. For example, this error occurs if an attempt is made to
           assign the value NULL to a variable declared NOT NULL, or if an
           attempt is made to assign an integer larger than 99 to a variable
           declared NUMBER(2).
*Action:   Change the data, how it is manipulated, or how it is declared so
           that values do not violate constraints.

We get the ORA-06502 error.

This error message doesn’t give us much more information. But, we can look at the code on line 6, as indicated by the message. We can see we have a variable that has a NOT NULL constraint, and the variable is NULL.

To be sure, we can output some text in our demo when it is null.

CREATE OR REPLACE PROCEDURE TestNonNull
AS
  testNumber NUMBER(4) NOT NULL := 10;
  nullValue NUMBER(4) := NULL;
BEGIN
  IF (nullValue IS NULL) THEN
    dbms_output.put_line('Value is null!');
  ELSE
    testNumber := nullValue;
  END IF;
END;

Now let’s call the procedure.

EXEC TestNonNull;
Value is null!

The output shows the text message, indicating the value is null.

ORA-06502 character string buffer too small

This version of the error can occur if you set a character variable to a value larger than what it can hold.

When you declare character variables (CHAR, VARCHAR2, for example), you need to specify the maximum size of the value. If a value is assigned to this variable which is larger than that size, then this error will occur.

For example:

DECLARE
  charValue VARCHAR2(5);
BEGIN
  charValue := 'ABCDEF';
END;

If I compile this code, I get an error:

ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 4

This happens because the variable is 5 characters long, and I’m setting it to a value which is 6 characters long.

You could also get this error when using CHAR data types.

DECLARE
  charValue CHAR(5);
BEGIN
  charValue := 'A';
  charValue := charValue || 'B';
END;
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 5

This error happens because the CHAR data type uses the maximum number of characters. It has stored the value of A and added 4 space characters, up until its maximum value of 5.

When you try to concatenate a value of B to it, the resulting value is ‘A    B’, which is 6 characters.

To resolve this, use a VARCHAR2 variable instead of a CHAR, and ensure the maximum size is enough for you.

ORA-06502: pl/sql: numeric or value error: null index table key value

Sometimes you might get this error message with the ORA-06502 error:

ORA-06502: pl/sql: numeric or value error: null index table key value

This means that either:

  • Your index variable is not getting initialized, or
  • Your index variable is getting set to NULL somewhere in the code.

Check your code to see that neither of these two situations are happening.

ORA-06502: pl/sql: numeric or value error: bulk bind: truncated bind

You might also get this specific error message:

ORA-06502: pl/sql: numeric or value error: bulk bind: truncated bind

This is caused by an attempt to SELECT, UPDATE, or INSERT data into a table using a PL/SQL type where a column does not have the same scale as the column in the table.

For example, you may have declared a variable in PL/SQL to be VARCHAR2(100), but your table is only a VARCHAR2(50) field. You may get this error then.

You may also get this error because some data types in PL/SQL have different lengths in SQL.

To resolve this, declare your variables as the same type as the SQL table:

type t_yourcol is table of yourtable.yourcol%TYPE;

So, that’s how you resolve the ORA-06502 error.

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

Learn the cause and how to resolve the ORA-06502 error message in Oracle.

Description

When you encounter an ORA-06502 error, the following error message will appear:

  • ORA-06502: PL/SQL: numeric or value error

Cause

You tried to execute a statement that resulted in an arithmetic, numeric, string, conversion, or constraint error.

The common reasons for this error are:

  1. You tried to assign a value to a numeric variable, but the value is larger than the variable can handle.
  2. You tried to assign a non-numeric value to a numeric variable and caused a conversion error.

Resolution

Let’s look at three options on how to resolve the ORA-06502 error:

Option #1 — Value too large

In our first option, this error occurs when you try to assign a value to a numeric variable, but the value is larger than the variable can handle.

For example, if you created a procedure called TestProc as follows:

SQL> CREATE OR REPLACE PROCEDURE TestProc
  2  AS
  3    v_number number(2);
  4  BEGIN
  5    v_number := 100;
  6  END;
  7  /

Procedure created.

This procedure was successfully created. But when we try to execute this procedure, we will get an ORA-06502 error as follows:

SQL> execute TestProc();
BEGIN TestProc(); END;

*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: number precision too large
ORA-06512: at "EXAMPLE.TESTPROC", line 5
ORA-06512: at line 1

The first line of the error message (ie: ORA-06502) indicates the error that occurred, while the second line of the error message (ie: ORA-06512) indicates that the error occurred at line 5 of the PLSQL code.

In this example, you’ve tried to assign a 3 digit number to a variable called v_number that can only handle 2 digits. You could correct this error by redefining the v_number variable as number(3).

SQL> CREATE OR REPLACE PROCEDURE TestProc
  2  AS
  3    v_number number(3);
  4  BEGIN
  5    v_number := 100;
  6  END;
  7  /

Procedure created.

And now when we execute our TestProc procedure, the ORA-06502 error has been resolved.

SQL> execute TestProc();

PL/SQL procedure successfully completed.

Option #2 — Conversion error

In our second option, this error occurs if you are trying to assign a non-numeric value to a numeric variable.

For example, if you created a procedure called TestProc as follows:

SQL> CREATE OR REPLACE PROCEDURE TestProc
  2  AS
  3    v_number number(2);
  4  BEGIN
  5    v_number := 'a';
  6  END;
  7  /

Procedure created.

This procedure was successfully created. But when we try to execute this procedure, we will get an ORA-06502 error as follows:

SQL> execute TestProc();
BEGIN TestProc(); END;

*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at "EXAMPLE.TESTPROC", line 5
ORA-06512: at line 1

In this example, the value of ‘a’ does not properly convert to a numeric value. You can correct this error by assigning the variable called v_number a proper numeric value.

SQL> CREATE OR REPLACE PROCEDURE TestProc
  2  AS
  3    v_number number(2);
  4  BEGIN
  5    v_number := ASCII('a');
  6  END;
  7  /

Procedure created.

And now when we execute our TestProc procedure, the ORA-06502 error has been resolved.

SQL> execute TestProc();

PL/SQL procedure successfully completed.

Option #3 — Assigning NULL to a NOT NULL constrained variable

In our third option, this error occurs if you are trying to assign a NULL value to a NOT NULL constrained variable.

For example, if you created a procedure called TestProc as follows:

SQL> CREATE OR REPLACE PROCEDURE TestProc
  2  AS   
  3    v_non_nullable_variable VARCHAR2(30) NOT NULL := '5';
  4    v_null_variable         VARCHAR2(30)          := NULL;
  5  BEGIN
  6    v_non_nullable_variable := v_null_variable;
  7  EXCEPTION
  8    WHEN OTHERS THEN
  9      dbms_output.put_line(SQLERRM);
  10 END;
  11 /

Procedure created.

This procedure was successfully created. But when we try to execute this procedure, we will get an ORA-06502 error as follows:

ORA-06502: PL/SQL: numeric or value error

In this example, you can not assign a NULL value to the variable called v_non_nullable_variable. You can correct this error removing NOT NULL from the variable declaration of the v_non_nullable_variable as follows:

SQL> CREATE OR REPLACE PROCEDURE TestProc
  2  AS   
  3    v_non_nullable_variable VARCHAR2(30) := '5';
  4    v_null_variable         VARCHAR2(30) := NULL;
  5  BEGIN
  6    v_non_nullable_variable := v_null_variable;
  7  EXCEPTION
  8    WHEN OTHERS THEN
  9      dbms_output.put_line(SQLERRM);
  10 END;
  11 /

Procedure created.

Понравилась статья? Поделить с друзьями:
  • Pl sql numeric or value error character string buffer too small перевод
  • Pl sql hex to raw conversion error
  • Pl sql format error backtrace
  • Pkt loss pubg как исправить
  • Pkgj ps vita ошибка 0x80436007