Ошибка ora 01438 value larger than specified precision allowed for this column

We get sometimes the following error from our partner’s database:

<i>ORA-01438: value larger than specified precision allows for this column</i>

The full response looks like the following:

<?xml version="1.0" encoding="windows-1251"?>
<response>
  <status_code></status_code>
  <error_text>ORA-01438: value larger than specified precision allows for this column ORA-06512: at &quot;UMAIN.PAY_NET_V1_PKG&quot;, line 176 ORA-06512: at line 1</error_text>
  <pay_id>5592988</pay_id>
  <time_stamp></time_stamp>
</response>

What can be the cause for this error?

Kiquenet's user avatar

Kiquenet

14.4k35 gold badges147 silver badges243 bronze badges

asked Oct 8, 2008 at 4:30

user11104's user avatar

1

The number you are trying to store is too big for the field. Look at the SCALE and PRECISION. The difference between the two is the number of digits ahead of the decimal place that you can store.

select cast (10 as number(1,2)) from dual
             *
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column

select cast (15.33 as number(3,2)) from dual
             *
ERROR at line 1:
ORA-01438: value larger than specified precision allowed for this column

Anything at the lower end gets truncated (silently)

select cast (5.33333333 as number(3,2)) from dual;
CAST(5.33333333ASNUMBER(3,2))
-----------------------------
                         5.33

answered Apr 29, 2010 at 23:44

Gary Myers's user avatar

Gary MyersGary Myers

34.9k3 gold badges49 silver badges74 bronze badges

1

The error seems not to be one of a character field, but more of a numeric one. (If it were a string problem like WW mentioned, you’d get a ‘value too big’ or something similar.) Probably you are using more digits than are allowed, e.g. 1,000000001 in a column defined as number (10,2).

Look at the source code as WW mentioned to figure out what column may be causing the problem. Then check the data if possible that is being used there.

answered Oct 8, 2008 at 4:56

Thorsten's user avatar

ThorstenThorsten

12.9k17 gold badges60 silver badges79 bronze badges

Further to previous answers, you should note that a column defined as VARCHARS(10) will store 10 bytes, not 10 characters unless you define it as VARCHAR2(10 CHAR)

[The OP’s question seems to be number related… this is just in case anyone else has a similar issue]

answered Oct 8, 2008 at 6:49

cagcowboy's user avatar

cagcowboycagcowboy

29.8k11 gold badges69 silver badges93 bronze badges

1

This indicates you are trying to put something too big into a column. For example, you have a VARCHAR2(10) column and you are putting in 11 characters. Same thing with number.

This is happening at line 176 of package UMAIN. You would need to go and have a look at that to see what it is up to. Hopefully you can look it up in your source control (or from user_source). Later versions of Oracle report this error better, telling you which column and what value.

Dave Jarvis's user avatar

Dave Jarvis

30.3k40 gold badges178 silver badges315 bronze badges

answered Oct 8, 2008 at 4:35

WW.'s user avatar

WW.WW.

23.7k13 gold badges94 silver badges121 bronze badges

0

FYI:
Numeric field size violations will give
ORA-01438: value larger than specified precision allowed for this column

VARCHAR2 field length violations will give
ORA-12899: value too large for column…

Oracle makes a distinction between the data types of the column based on the error code and message.

answered Jun 27, 2016 at 15:14

Priyome's user avatar

One issue I’ve had, and it was horribly tricky, was that the OCI call to describe a column attributes behaves diffrently depending on Oracle versions. Describing a simple NUMBER column created without any prec or scale returns differenlty on 9i, 1Og and 11g

answered Oct 8, 2008 at 5:12

Robert Gould's user avatar

Robert GouldRobert Gould

68.6k61 gold badges186 silver badges271 bronze badges

From http://ora-01438.ora-code.com/ (the definitive resource outside of Oracle Support):

ORA-01438: value larger than specified precision allowed for this column
Cause: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.
Action: Enter a value that complies with the numeric column’s precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.

http://ora-06512.ora-code.com/:

ORA-06512: at stringline string
Cause: Backtrace message as the stack is unwound by unhandled exceptions.
Action: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.

answered Oct 8, 2008 at 14:00

warren's user avatar

warrenwarren

32.4k21 gold badges85 silver badges123 bronze badges

It might be a good practice to define variables like below:

v_departmentid departments.department_id%TYPE;

NOT like below:

v_departmentid NUMBER(4)

answered Apr 30, 2010 at 2:00

gokhant's user avatar

gokhantgokhant

961 silver badge3 bronze badges

It is also possible to get this error code, if you are using PHP and bound integer variables (oci_bind_by_name with SQLT_INT).
If you try to insert NULL via the bound variable, then you get this error or sometimes the value 2 is inserted (which is even more worse).

To solve this issue, you must bind the variable as string (SQLT_CHR) with fixed length instead. Before inserting NULL must be converted into an empty string (equals to NULL in Oracle) and all other integer values must be converted into its string representation.

answered Jan 13, 2022 at 11:13

David Gausmann's user avatar

Following is my code, I dont understand what I’m doing wrong. Any help will be greatly appreciated

CREATE OR REPLACE
PROCEDURE COMP_LATE_FEE(LATE_APT_FINE IN NUMBER, LATE_GRG_FINE IN NUMBER)
AS
DIFF NUMBER;
TYPE MBCUR IS REF CURSOR RETURN MONTHLY_BILL%ROWTYPE;
MONBILL MBCUR;
MBREC MONTHLY_BILL%ROWTYPE;
BEGIN
--DIFF := FLOOR(SYSDATE - (TRUNC(SYSDATE,'MM')));
--DBMS_OUTPUT.PUT_LINE(DIFF);

OPEN MONBILL FOR
    -- checking the status of all last month's bills
    SELECT * FROM MONTHLY_BILL
    WHERE STATUS = 'PENDING' AND SYSDATE > ED_DT;
FETCH MONBILL INTO MBREC;
    -- adding the late fee amount for any bills that are past the due date
    -- due date = last day of the month
    DIFF := FLOOR(ABS(MBREC.ED_DT - (TRUNC(SYSDATE,'MM'))));
    UPDATE MONTHLY_BILL
    SET LATE_FEE = DIFF * LATE_APT_FINE
    WHERE BILL_NUM = MBREC.BILL_NUM;
    -- if a garage is rented by the resident then the respective additional fee is included
    IF (MBREC.GARAGE_RENT != 0) THEN
        UPDATE MONTHLY_BILL
        SET LATE_FEE = LATE_FEE + DIFF * LATE_GRG_FINE
        WHERE BILL_NUM = MBREC.BILL_NUM;
    END IF;

    COMMIT;
CLOSE MONBILL;
 END;
/

The procedure compiled without any err. But I get the following err when i call the proc

BEGIN
COMP_LATE_FEE(70,20);
END;
/

Error report:

ORA-01438: value larger than specified precision allowed for this column
ORA-06512: at "LALLURI.COMP_LATE_FEE", line 19
ORA-06512: at line 2
01438. 00000 -  "value larger than specified precision allowed for this column"
*Cause:    When inserting or updating records, a numeric value was entered
           that exceeded the precision defined for the column.
*Action:   Enter a value that complies with the numeric column's precision,
           or use the MODIFY option with the ALTER TABLE command to expand
           the precision.

totn Oracle Error Messages


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

Description

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

  • ORA-01438: value larger than specified precision allows for this column

Cause

You tried to assign a numeric value to a column, but the value was larger than the column will allow. This occurred during either an INSERT or an UPDATE statement.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

Assign a smaller precision value to the column.

Option #2

Modify the definition of the table to allow for a higher precision number in the column. This can be done with a ALTER TABLE statement.

For example, if you had a table called suppliers defined as follows:

CREATE TABLE suppliers
( supplier_id number(5) not null,
  supplier_name varchar2(50) not null
);

And you tried to execute the following INSERT statement:

INSERT into suppliers
(supplier_id, supplier_name)
VALUES (123456, 'IBM');

You would receive the following error message:

Oracle PLSQL

You could correct the error with either of the following solutions:

Solution #1

You can correct the INSERT statement to assign a smaller precision value to the supplier_id column as follows:

INSERT into suppliers
(supplier_id, supplier_name)
VALUES (12345, 'IBM');

Solution #2

You can modify the table definition of the suppliers table to allow for a 6 digit precision number.

ALTER TABLE suppliers
 MODIFY supplier_id number(6);

You may also want to
see this article about the ORA-12899 which is returned if a value larger than
column’s width is inserted in the column. Similarly, ORA-01438 is returned if value being inserted is larger than what
is defined for the NUMBER datatype column. Number datatype columns are defined
in precision and scale (NUMBER(p,s)). If you define a number column as “NUMBER(5,2)”,
it would mean that maximum width of the data could be 5 digits, out of which 2
will be decimal part (for example 123.45). Following are some examples that
explain this concept further.

— In the following example,
the inserted value should only have 2 digits, and both digits should be in
the decimal part of the number

SQL>
create table test (sal number(2,2));

Table
created.

SQL>
insert into test values(2.3333);

insert
into test values(2.3333)

                        *

ERROR
at line 1:

ORA-01438:
value larger than specified precision allowed for this column

SQL>
insert into test values(2.3);

insert
into test values(2.3)

                        *

ERROR
at line 1:

ORA-01438:
value larger than specified precision allowed for this column

SQL>
insert into test values(2);

insert
into test values(2)

                        *

ERROR
at line 1:

ORA-01438:
value larger than specified precision allowed for this column

SQL>
insert into test values(.2);

1
row created.

SQL>

— In the following example,
the inserted value should only have 2 digits for precision part only as no
decimal could be inserted in this column, although INSERT statement would
succeed if decimal value is mentioned.

SQL>
create table test (sal number(2));

Table
created.

SQL>
insert into test values(2.1);

1
row created.

SQL>
insert into test values(2.11);

1
row created.

SQL>
insert into test values(2.111);

1
row created.

SQL>
insert into test values(2.1110000);

1
row created.

SQL>
insert into test values(22.1110000);

1
row created.

SQL>
insert into test values(223.1110000);

insert
into test values(223.1110000)

                        *

ERROR
at line 1:

ORA-01438:
value larger than specified precision allowed for this column

SQL>
select * from test;

       SAL

———-

         2

         2

         2

         2

        22

— In the following example,
maximum 6 digits could be inserted in the column out of which 4 have to be
decimal part. As soon as we try to insert 3 digits in precision part,
ORA-01438 would be returned because 4 places have to be reserved for the decimal
part.

SQL>
create table test (sal number(6,4));

Table
created.

SQL>
insert into test values(25.65743);

1
row created.

SQL>
insert into test values(2534333.65743);

insert
into test values(2534333.65743)

                        *

ERROR
at line 1:

ORA-01438:
value larger than specified precision allowed for this column

SQL>
insert into test values(253433.65743);

insert
into test values(253433.65743)

                        *

ERROR
at line 1:

ORA-01438:
value larger than specified precision allowed for this column

SQL>
insert into test values(2534.65743);

insert
into test values(2534.65743)

                        *

ERROR
at line 1:

ORA-01438:
value larger than specified precision allowed for this column

SQL>
insert into test values(2.65743);

1
row created.

SQL>
insert into test values(22.65743);

1
row created.

SQL>
insert into test values(223.65743);

insert
into test values(223.65743)

                        *

ERROR
at line 1:

ORA-01438:
value larger than specified precision allowed for this column

SQL>
insert into test values(243.5);

insert
into test values(243.5)

                        *

ERROR
at line 1:

ORA-01438:
value larger than specified precision allowed for this column

SQL>
select * from test;

       SAL

———-

   25.6574

    2.6574

   22.6574

Мы иногда получаем следующую ошибку из нашей базы данных партнеров:

Полный ответ выглядит следующим образом:

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

sql database oracle plsql ora-01438

8 ответов

Число, которое вы пытаетесь сохранить, слишком велико для поля. Посмотрите на ШКАЛА и ТОЧНОСТЬ. Разница между ними — это количество цифр перед десятичной точкой, которую вы можете сохранить.

Все, что находится на нижнем конце, усекается (тихо)

6 Thorsten [2008-10-08 07:56:00]

Ошибка, похоже, не является одним из полей символов, но более числовым. (Если бы это была проблема с строкой, подобная WW, вы получили бы «значение слишком большое» или что-то подобное.) Вероятно, вы используете больше цифр, чем разрешено, например. 1,000000001 в столбце, определяемом как число (10,2).

Посмотрите на исходный код, как упоминалось в WWW, чтобы выяснить, какой столбец может вызвать проблему. Затем проверьте данные, если это возможно.

3 WW. [2008-10-08 07:35:00]

Это означает, что вы пытаетесь помещать нечто слишком большое в столбец. Например, у вас есть столбец VARCHAR2 (10), и вы помещаете 11 символов. То же самое с номером.

Это происходит на линии 176 пакета UMAIN. Вам нужно будет пойти и посмотреть на это, чтобы посмотреть, что это значит. Надеюсь, вы сможете найти его в своем источнике управления (или из user_source). Более поздние версии Oracle лучше сообщают эту ошибку, сообщая вам, какой столбец и какое значение.

В дополнение к предыдущим ответам вы должны заметить, что столбец, определенный как VARCHARS (10), будет хранить 10 байтов, а не 10 символов, если вы не определяете его как VARCHAR2 (10 CHAR)

[Вопрос OP, похоже, связан с числом. это на всякий случай, если у кого-то есть аналогичная проблема]

Одна из проблем, которые у меня были, и это было ужасно сложно, заключалось в том, что вызов OCI для описания атрибутов столбца ведет себя по-разному в зависимости от версий Oracle. Описывая простой столбец NUMBER, созданный без каких-либо запросов или масштабирования, возвращает differenlty на 9i, 1Og и 11g

1 warren [2008-10-08 17:00:00]

Из http://ora-01438.ora-code.com/ (окончательный ресурс за пределами поддержки Oracle):

ORA-01438: значение, превышающее указанную точность, разрешено для этого столбца
Причина. При вставке или обновлении записей вводилось числовое значение, которое превышало точность, определенную для столбца.
Действие. Введите значение, соответствующее точности числового столбца, или используйте параметр MODIFY с помощью команды ALTER TABLE, чтобы увеличить точность.

ORA-06512: при строковой строке

Причина: сообщение Backtrace как стек разматывается необработанными исключениями.
Действие. Исправьте проблему, вызывающую исключение, или напишите обработчик исключений для этого условия. Или вам может потребоваться обратиться к администратору приложения или администратору базы данных.

0 gokhant [2010-04-30 05:00:00]

Это может быть хорошей практикой для определения переменных, как показано ниже:

НЕ нравится ниже:

0 Priyome [2016-06-27 18:14:00]

FYI: Числовые нарушения размера поля дадут ORA-01438: значение, превышающее указанную точность, разрешено для этого столбца

Нарушения длины поля VARCHAR2 ORA-12899: значение слишком велико для столбца.

Oracle делает различие между типами данных столбца на основе кода ошибки и сообщения.

ORA-01438 при выгрузке на кассу : Супермаг Плюс (Супермаг 2000)

В работе кассового модуля произошел сбой. Сообщения об ошибках см. ниже.
Запись 1. Код=80040e57h (1438) [Microsoft OLE DB Provider for Oracle]:
ORA-01438: значение больше, чем позволяет заданная для этого столбца точность
ORA-06512: на «SUPERMAG.CASH», line 2127
ORA-06512: на line 1

Запись 2. Код=80004005h (0) [SmLibaryBase trace]:
begin Supermag.Cash.FillDiscLimitCardForPOS(10,11); end;

Судя по всему ошибка при заполнении пределов скидок. Как вычислить, что ему не нравится?

а в других магазинах работат почему?

Добавлено через 27 минут 25 секунд
а в какой табличке и как называется параметр Мин.цена?

whitewizard
Посмотреть профиль
Где был?
Найти ещё сообщения от whitewizard

нее. это когда на кассу выгружаешь

Добавлено через 58 секунд
короче. на самом деле проблема была в том, что мин.цена была больше текущей розничной.

сохранить исключения не захватывает полное описание ошибки для ORA-01438

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

Ответы (1)

Как заявляет Oracle

Добавьте предложение SAVE EXCEPTIONS в свой оператор FORALL, если вы хотите, чтобы механизм выполнения PL / SQL выполнял все операторы DML, сгенерированные FORALL, даже если один или несколько завершаются с ошибкой. Если вы используете ИНДЕКСЫ OF, вам нужно будет немного постараться, чтобы вернуться к заявлению о нарушении.

Итак, SAVE EXCEPTIONS выполняет то, что должно делать, поэтому полностью выполняет весь FORALL, не вызывая никаких проблем до конца. Ваша проблема здесь — ORA-01438: value larger than specified precision allowed for this column . Это исключение никогда не проинформирует затронутый столбец. Чтобы зафиксировать проблемный столбец, у вас есть несколько вариантов.

SQL

В SQL, например, при использовании sqlplus, вы получаете указание, какой столбец является ответственным, поскольку он отмечен звездочкой, хотя столбец не назван явно в исключении.

PL / SQL

В PL / SQL исключение обрабатывается модулем EXCEPTION, который управляет SQLCODE и SQLERRM, связанными с ошибкой. В этой ошибке нет никакого указания на столбец:

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

РЕГИСТРАЦИЯ ОШИБОК DML

DML ERROR LOGGING — это функция, которая четко вписывается в ваш сценарий. Вы должны применить предложение LOG ERRORS INTO ERROR_TABLE после создания таблицы ошибок.

В вашем конкретном коде вы должны:

1. Создайте ТАБЛИЦУ ОШИБОК для своей таблицы exception_test с помощью DBMS_ERRLOG.

2. Измените ВСТАВИТЬ ЗАЯВЛЕНИЕ, чтобы добавить предложение LOG ERRORS INTO YOUR_ERROR_TABLE и удалить часть SAVE EXCEPTIONS . После использования DML_ERROR_LOGGING все исключения будут сохранены в таблице журнала ошибок.

  • Ошибка ora 01422 точная выборка возвращает количество строк больше запрошенного
  • Ошибка ora 01033 oracle initialization or shutdown in progress
  • Ошибка ora 01008 not all variables bound
  • Ошибка ora 01002 fetch out of sequence
  • Ошибка ora 00972 identifier is too long