I tried the following code different ways, like by taking out the while or the if, but when I put both together (if and while), I always get the error at the end…
undefine numero
set serveroutput on
accept numero prompt 'Type # between 100 and 999: '
declare
i number:=1;
a char(25);
b char(1);
c varchar2(10);
d number;
begin
c := №
d := length(c);
b := substr(c, i, 1);
while i <= d loop
if b = '1' then
a:= a||'one ';
end if;
i := i+1;
end loop;
dbms_output.put_line('The number is '||a);
end;
/
ERROR:
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 13
06502. 00000 - "PL/SQL: numeric or value error%s"
FIXED by changing how I declared the variable «a» to:
a varchar2(2000);
*Notice that here, the significant change is to use VARCHAR2 instead of CHAR (not the bigger length). According to @user272735 ‘s answer, that’s the key.
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:
- A value is being assigned to a numeric variable, but the value is larger than what the variable can handle.
- A non-numeric value is being assigned to a numeric variable.
- 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.
While you’re here, if you want an easy-to-use list of the main features in Oracle SQL, get my SQL Cheat Sheet 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:
- Ensure the value coming in is a number and not a string.
- Convert your string to a number using TO_NUMBER (the conversion might happen implicitly but this may help).
- Convert your string to the ASCII code that represents the string using the ASCII function.
- 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.
While you’re here, if you want an easy-to-use list of the main features in Oracle SQL, get my SQL Cheat Sheet here:
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 tells you that PL/SQL engine cannot convert a string into a number. Which means, an arithmetic, numeric, string, conversion, or constraint error occurred. Let’s see a normal case first.
SQL> set serveroutput on;
SQL> declare
2 v_num number;
3 begin
4 v_num := 123;
5 dbms_output.put_line('The number is ' || v_num);
6 end;
7 /
The number is 123
PL/SQL procedure successfully completed.
A number 123 is assigned to variable V_NUM which accept only NUMBER type. So there’s no conversion needed. But what if we assign a string to the variable?
SQL> declare
2 v_num number;
3 begin
4 v_num := '123';
5 dbms_output.put_line('The number is ' || v_num);
6 end;
7 /
The number is 123
PL/SQL procedure successfully completed.
As you can see, PL/SQL engine converted the string into a number, then assigned it into the variable.
Now, let’s try some basic arithmetic expressions.
SQL> declare
2 v_num number;
3 begin
4 v_num := 2 + 2;
5 dbms_output.put_line('The number is ' || v_num);
6 end;
7 /
The number is 4
PL/SQL procedure successfully completed.
OK, the variable accepts value, the result of evaluation, no ORA-06502. What if we use it as a string?
SQL> declare
2 v_num number;
3 begin
4 v_num := '2 + 2';
5 dbms_output.put_line('The number is ' || v_num);
6 end;
7 /
declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 4
PL/SQL engine tried to convert the string into a number, but it failed with ORA-06502. This time, V_NUM cannot accept the result.
The solution to this type of error is to avoid implicit type conversion if possible.
B. Numeric Operator Precedence
To better understand ORA-06502, let’s see a more advanced topic about operator precedence in Oracle database. In the following example, we tried to output a string that concatenate an arithmetic.
SQL> begin
2 dbms_output.put_line('The number is ' || 2 + 2);
3 end;
4 /
begin
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 2
ORA-06502 was thrown eventually. Since || (concatenation) and + (addition) operators are at the same level of operator precedence, PL/SQL engine will evaluate them in the order of presence.
First, it concatenated «The number is » and «2» into «The number is 2», which was successful, but when it tried to add the last value «2», it failed to convert the former string into a number and threw ORA-06502.
Solutions
1. Rearrange the Output
We should make PL/SQL engine deal with the numeric evaluation first, then the concatenation by rearranging the output.
SQL> begin
2 dbms_output.put_line(2 + 2 || ' is the number.');
3 end;
4 /
4 is the number.
PL/SQL procedure successfully completed.
This time, the expression is good because the order of presence of operators has been changed.
2. Override Operator Precedence
Beside rearranging the order of presence, how can we make the latter take the precedence over the former to fix the problem? Here is the trick for our PL/SQL block of codes.
SQL> begin
2 dbms_output.put_line('The number is ' || (2 + 2));
3 end;
4 /
The number is 4
PL/SQL procedure successfully completed.
As you can see, we used a parenthesis to override operator precedence. The evaluation will start from the highest precedence which is 2 + 2 numeric value inside the parentheses to the rest according to their operator precedence defined in Oracle. This is how we escape from ORA-06502.
In PL/SQL, if multiple parentheses are used in your expression, the evaluation will start from the inner to the outer.
A very similar error that you might see in your statements is ORA-01722: invalid number, which is also related to conversion issues of numeric values.
I have a below Package which is giving error
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
Please let me know what is going wrong here.
CREATE OR REPLACE PACKAGE BODY PKG_H
IS
PROCEDURE PROC_SUBMIT_H
(
Pout_Rqst_Id OUT NVARCHAR2,
Pout_err_cd OUT VARCHAR2,
Pout_err_msg OUT VARCHAR2,
Pin_Rqst_Type_Id IN NUMBER,
Pin_Attachment IN NVARCHAR2,
Pin_Brand_Id IN NVARCHAR2,
Pin_Prop_Id IN NVARCHAR2,
-- Pin_Htl_Stat_Rqst_Typ_ID IN NUMBER,
Pin_Orcl_Acct_Num IN NVARCHAR2, -- NUMBER, /* Changed on 22.09.2011,as stated by FIS Team */
Pin_ORCL_User_Name IN NVARCHAR2,
Pin_Rstn_Id IN NUMBER,
Pin_Rstn_Name IN NVARCHAR2,
Pin_Rstn_Start_Date IN DATE,
Pin_Rstn_End_Date IN DATE,
-- Pin_Change_Type_Ind IN NVARCHAR2,
Pin_Trans_Time_Orcl IN TIMESTAMP,
Pin_Fis_Acct_Stat_Prsnt_Id IN NUMBER,
Pin_Fis_Acct_Future_Stat IN NUMBER,
Pin_Auto_Ind IN NVARCHAR2,
-- Pin_Stat_Change_Resn_ID IN NUMBER, /* changed due to ETL requirement as on 17.09.2011 */
Pin_Stat_Change_Resn_Desc IN NVARCHAR2, /* changed due to ETL requirement as on 17.09.2011 */
Pin_Brand_Dot_Com_Ind IN NVARCHAR2,
-- Pin_Expdt_Ind IN NVARCHAR2,
-- Pin_Expdt_Dt IN DATE,
Pin_Rqstr_Id IN NVARCHAR2,
Pin_Impn_Id IN NUMBER,
-- Pin_Agent_Id IN NVARCHAR2, /* Changed as on 22.09.2011 */
-- Pin_Agent_Name IN NVARCHAR2, /* Changed as on 22.09.2011 */
Pin_File_Name IN NVARCHAR2,
Pin_Prov_Date IN DATE
-- Pin_Rqst_Stat_ID IN NUMBER
-- Pin_Prov_Time IN DATE
)
IS
-- lv_err_cd VARCHAR2(10);
-- lv_err_msg VARCHAR2(4000);
Ln_Cnt NUMBER;
DUP_VAL EXCEPTION;
lv_rqst_id NVARCHAR2(20);
Ln_rqst_stat_id_it NUMBER;
Ln_rqst_stat_id_Q NUMBER;
Ln_rqst_category_id NUMBER;
Ln_Stat_Change_Resn_Id NUMBER;
-- Ln_Htl_Stat_Rqst_Typ_Id NUMBER;
lt_data_01 STRINGTABLETYPE := STRINGTABLETYPE();
lt_data_02 STRINGTABLETYPE := STRINGTABLETYPE();
BEGIN
SELECT fnc_gen_request_id
INTO Lv_rqst_id
FROM dual;
SELECT rqst_stat_id
INTO Ln_rqst_stat_id_it
FROM rqst_stat_mst
WHERE rqst_stat_desc = 'In Transmit';
SELECT rqst_stat_id
INTO Ln_rqst_stat_id_Q
FROM rqst_stat_mst
WHERE rqst_stat_desc = 'Pending';
SELECT COUNT(1)
INTO Ln_Cnt
FROM HOTEL_STAT_RQST
WHERE FILE_NAME=Pin_File_Name;
IF Ln_Cnt >0 then
RAISE DUP_VAL;
END IF;
IF Pin_Stat_Change_Resn_Desc IS NOT NULL THEN
SELECT STAT_CHANGE_RESN_ID
INTO Ln_Stat_Change_Resn_Id
FROM STAT_CHANGE_RESN_MST
WHERE UPPER(STAT_CHANGE_RESN_DESC)=UPPER(TRIM(Pin_Stat_Change_Resn_Desc));
END IF;
DELETE
FROM HOTEL_STAT_RQST
WHERE RQST_ID=lv_rqst_id;
INSERT INTO HOTEL_STAT_RQST
(RQST_ID
,RQST_TYPE_ID
,RQST_STAT_ID
,BRAND_ID
,PROPERTY_ID
,STAT_CHANGE_RESN_ID
-- ,HOTEL_STAT_RQST_TYPE_ID
,ORCL_ACCT_NUM
,ORCL_USER_NAME
,TRANS_TIME_ORCL
,FIS_ACCOUNT_STATUS_PRESENT_ID
,FIS_ACCT_FUTURE_STAT
,RSTCTN_ID
,RSTCTN_NAME
,RSTCTN_STRT_DT
,RSTCTN_END_DT
-- ,RSTCTN_PREV_STRT_DT /* SCHEMA CHANGED */
-- ,RSTCTN_PREV_END_DT /* SCHEMA CHANGED */
-- ,PREV_RSTN_ID /* SCHEMA CHANGED */
,AUTO_IND
-- ,CHANGE_TYPE_IND
,BRAND_DOT_COM_IND
,RQSTR_ID
,IMPN_ID
,EXPDT_IND
,EXPDT_DT
-- ,PROVSN_STAT /* SCHEMA CHANGED */
-- ,PROVSN_TIME /* SCHEMA CHANGED */
,CREATED_ON
,UPDATED_BY
,UPDATED_ON
,FILE_NAME
,PROV_DATE
)
VALUES
(
lv_rqst_id
,Pin_Rqst_Type_Id
,Ln_rqst_stat_id_it
,Pin_Brand_Id
,Pin_Prop_Id
,Ln_Stat_Change_Resn_Id /* changed due to ETL requirement as on 17.09.2011 */
-- ,Pin_Htl_Stat_Rqst_Typ_ID
,Pin_Orcl_Acct_Num
,Pin_ORCL_User_Name
,Pin_Trans_Time_Orcl
,Pin_Fis_Acct_Stat_Prsnt_Id
,Pin_Fis_Acct_Future_Stat
,Pin_Rstn_Id
,Pin_Rstn_Name
,Pin_Rstn_Start_Date
,Pin_Rstn_End_Date
-- ,NULL /* SCHEMA CHANGED */
-- ,NULL /* SCHEMA CHANGED */
-- ,NULL /* SCHEMA CHANGED */
,Pin_Auto_Ind
-- ,Pin_Change_Type_Ind
,Pin_Brand_Dot_Com_Ind
,Pin_Rqstr_Id
,Pin_Impn_Id
,NULL
,NULL
-- ,NULL /* SCHEMA CHANGED */
-- ,Pin_Prov_Time /* SCHEMA CHANGED */
,SYSDATE
,Pin_Rqstr_Id
,SYSDATE
,Pin_File_Name
,Pin_Prov_Date
);
IF Pin_Attachment IS NOT NULL THEN
DELETE
FROM attach_ref
WHERE rqst_id=lv_rqst_id;
SELECT CAST(SPLIT(Pin_Attachment,'|') AS STRINGTABLETYPE) INTO lt_data_01 FROM DUAL;
FOR i_outer IN 1..lt_data_01.COUNT LOOP
SELECT CAST(SPLIT(lt_data_01(i_outer),'~')AS STRINGTABLETYPE) INTO lt_data_02 FROM DUAL;
INSERT INTO attach_ref
(
rqst_id,
attach_id, -- SEQUENCE
attach_ind,
attach_file_name,
file_path,
ord_num
)
VALUES(
lv_rqst_id,
attach_id_seq.NEXTVAL, -- SEQUENCE
'REQUESTOR',
lt_data_02(1),
lt_data_02(2),
i_outer
);
END LOOP;
END IF;
DELETE FROM rqst_queue WHERE rqst_id=lv_rqst_id;
INSERT INTO rqst_queue
(
rqst_id,
prnt_rqst_id,
queu_start_time,
queu_end_time,
agnt_id,
agnt_name,
property_id,
src_sys,
tgt_sys,
queu_stat_ind
)
VALUES
(
lv_rqst_id,
NULL,
SYSDATE,
NULL,
NULL,
NULL,
Pin_Prop_Id,
'RQT',
'SFDC',
Ln_rqst_stat_id_Q
);
IF Pin_Rqst_Type_Id IS NOT NULL THEN
SELECT rqst_category_id
INTO ln_rqst_category_id
FROM rqst_type_mst
WHERE rqst_type_id = Pin_Rqst_Type_Id;
END IF;
DELETE
FROM rqst_sumry
WHERE rqst_id = lv_rqst_id;
INSERT INTO rqst_sumry
(
rqst_id,
rqst_type_id,
prnt_rqst_id,
brand_id,
property_id,
expdt_ind,
expdt_dt,
rqstr_id,
rqst_stat_id,
compln_dt,
estm_compln_time,
rqst_category_id,
submission_dt
)
VALUES
(
lv_rqst_id,
Pin_Rqst_Type_Id,
NULL,
Pin_Brand_Id,
Pin_Prop_Id,
NULL,
NULL,
Pin_Rqstr_Id,
Ln_rqst_stat_id_it,
NULL,
NULL,
ln_rqst_category_id,
SYSDATE
);
COMMIT;
Pout_Rqst_Id := lv_rqst_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
ROLLBACK;
Pout_err_cd := SQLCODE;
Pout_err_msg := 'STAT_CHANGE_RESN_MISMATCH';
WHEN DUP_VAL THEN
Pout_err_cd := SQLCODE;
Pout_err_msg := 'DUPLICATE';
WHEN OTHERS THEN
ROLLBACK;
Pout_err_cd := SQLCODE;
Pout_err_msg := SUBSTR(SQLERRM, 1 , 4000);
END PROC_SUBMIT_H;
END PKG_H;
/
Об этой ошибке: ORA-06502: числовая или значимая ошибка
FOR this_loop IN (SELECT field_A, field_B FROM TABLE_NAME WHERE num = i_num) LOOP IF this_loop.field_B BETWEEN 1 AND 3 THEN v_A := v_A || ' ' || this_loop.field_A; ELSIF this_loop.field_B BETWEEN 4 AND 8 THEN v_field_A := v_field_A || ' ' || this_loop.field_A; -- Error is at this line ELSIF this_loop.field_B BETWEEN 9 AND 15 THEN v_B := v_B || ' ' || this_loop.field_A; END IF; END LOOP;
Переменная обозначается как
v_field_A VARCHAR2 (100);
Что я знаю —
- Переменная v_field_A не может содержать значение более 100 символов.
- Результат, который я получаю от
SELECT
Запрос не может содержать более 10 символов.
Мой вопрос — как вообще можно решить эту проблему с пространственным буфером, когда символы находятся в пределах лимита varchar2? Я столкнулся с этой проблемой несколько лет назад, но в прошлый раз причиной был выход select
запрос. В нем было более 100 символов, и, следовательно, проблема с размером, но на этот раз не более 10 символов. Я в замешательстве. Любая помощь приветствуется
- сколько строк у вас в таблице?
- Есть более миллиона строк, но это происходит только с несколькими строками.
- Чтобы быть более конкретным, сколько строк извлекает цикл? 10 символов * 11 итераций цикла == вы столкнетесь с ошибкой, так как вы продолжаете конкатенировать значение переменной на каждой итерации
- почему нельзя увеличить размер v_field_A? это решит проблему
- @ Сатья Это зависит от обстоятельств. Обычно это не более 3-4 рядов.
Переменная v_field_A не может содержать значение более 100 символов.
Почему нет? Это очень возможно, так как вы сцепление переменная для каждой строки в КУРСОР ДЛЯ ПЕТЛИ.
Например,
SQL> DECLARE 2 v_name VARCHAR2(50); 3 BEGIN 4 FOR i IN 5 (SELECT ename FROM emp 6 ) 7 LOOP 8 v_name := v_name || i.ename; 9 END LOOP; 10 END; 11 / DECLARE * ERROR at line 1: ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at line 8
Использовать DBMS_OUTPUT чтобы увидеть текущий размер переменной и добавляемое новое значение.
Давайте отладим
SQL> DECLARE 2 v_name VARCHAR2(50); 3 BEGIN 4 FOR i IN 5 (SELECT ename FROM emp 6 ) 7 LOOP 8 dbms_output.put_line('Length of new value = '||LENGTH(i.ename)); 9 v_name := v_name || i.ename; 10 dbms_output.put_line('Length of variable = '||LENGTH(v_name)); 11 END LOOP; 12 END; 13 / Length of new value = 5 Length of variable = 5 Length of new value = 5 Length of variable = 10 Length of new value = 4 Length of variable = 14 Length of new value = 5 Length of variable = 19 Length of new value = 6 Length of variable = 25 Length of new value = 5 Length of variable = 30 Length of new value = 5 Length of variable = 35 Length of new value = 5 Length of variable = 40 Length of new value = 4 Length of variable = 44 Length of new value = 6 Length of variable = 50 Length of new value = 5
ошибка
DECLARE * ERROR at line 1: ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at line 9
Это довольно ясно, мы хотели объединить строку длиной 5
к переменной, объявленной как максимальный размер 50
, в настоящее время хранит значение размера 50
. следовательно, он выдает ошибку ORA-06502: PL/SQL: numeric or value error: character string buffer too small
.
- Поправьте меня если я ошибаюсь. если переменная может содержать более 50 или 100 символов. Проблема размера не должна существовать вовсе, верно?
- @PirateX Вы забываете тот факт, что вы объединяете значения в переменную в цикле, поэтому в какой-то момент при итерации по косякам он превышает заявленный размер. Я добавил в свой ответ пример.
- Хорошо, я думаю, что у меня есть идея. Это конкатенация, которая в какой-то момент превышает предел 100, вызывая ошибку. Правильно ?
- @PirateX Совершенно верно. Это то, что вы видите в DBMS_OUTPUT в примере, который я вам показал.
- @PirateX Пожалуйста, отметьте это как ответ, помогло бы и другим! Я вижу, что ни один из ваших вопросов никогда не был отмечен как отвеченный. Это хороший жест, и сообщество предлагает принять ответ, который решит вашу проблему. Удачи!
11 строк * 10 символов> 100 символов => ошибка — вы объединяете много строк по 10 символов вместе в одну из трех переменных. Один из них будет расти каждый раз в цикле.
Что мне не хватает?
Также остерегайтесь символов вместо байтов. В varchar2 каждый CHARACTER, вероятно, займет 2 байта.
Проверьте, сколько раз это условие выполняется и какие значения объединяются. Поскольку это объединяется несколько раз, существует вероятность того, что размер v_field_A превышает 50 символов.
ELSIF this_loop.field_B BETWEEN 4 AND 8 THEN v_field_A := v_field_A || ' ' || this_loop.field_A;
Чтобы решить эту проблему, вы можете увеличить размер этой переменной. Вы можете объявить varchar размером до 32 767 байт
Вы можете выполнить конкатенацию строк в SQL-запросе:
SELECT field_A, LISTAGG(CASE WHEN field_B BETWEEN 1 AND 3 THEN field_A END, ' ') WITHIN GROUP (ORDER BY field_A) as val1, LISTAGG(CASE WHEN field_B BETWEEN 4 AND 8 THEN field_A END, ' ') WITHIN GROUP (ORDER BY field_A) as val2, LISTAGG(CASE WHEN field_B BETWEEN 9 AND 15 THEN field_A END, ' ') WITHIN GROUP (ORDER BY field_A) as val3 FROM TABLE_NAME WHERE num = i_num;
Это сделано для упрощения вашего кода. Вы по-прежнему ограничены длиной строки Oracle. Вы можете обойти ограничение Oracle в PL / SQL с помощью CLOB, но в этом нет необходимости, если конечная строка состоит всего из нескольких сотен символов.
- 2 Даже
LISTAGG
имеет Ограничение SQL из4000
.
Ответ на ваш вопрос заключается в том, сколько раз цикл выполняется и сколько раз он входит в условие IF.
ПРИМЕР :
Состояние : МЕЖДУ 4 А ТАКЖЕ 8
this_loop.field_A: = ‘тест’;
Количество выполнений цикла = 100
Из-за КОНКАТИНАЦИЯ размер определенно вырастет более чем на 100 символов.
То же самое будет и с другими условиями LOOP.
Решение : Попробуйте использовать CLOB вместо того VARCHAR чтобы устранить эту проблему.
Ошибки Oracle очень наглядны. Если он вызывает ошибку, это в значительной степени объясняет сценарий: P.
Tweet
Share
Link
Plus
Send
Send
Pin