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

A SELECT INTO statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you’ll get a no_data_found exception. If it returns more than 1 row, you’ll get a too_many_rows exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO statement here.

Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I’m also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I’m assuming that there is a departmentID column in both tables)

BEGIN
  FOR rec IN (SELECT EMPLOYEE.EMPID, 
                     EMPLOYEE.ENAME, 
                     EMPLOYEE.DESIGNATION, 
                     EMPLOYEE.SALARY,  
                     DEPARTMENT.DEPT_NAME 
                FROM EMPLOYEE, 
                     DEPARTMENT 
               WHERE employee.departmentID = department.departmentID
                 AND EMPLOYEE.SALARY > 3000)
  LOOP
    DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
  END LOOP;
END;

I’m assuming that you are just learning PL/SQL as well. In real code, you’d never use dbms_output like this and would not depend on anyone seeing data that you write to the dbms_output buffer.

ORA-01422

ORA-01422: Выполняемая выборка возвращает более одной строки

Причина:

Вы пытались выполнить SELECT INTO и запрос вернул более чем одну запись.

Действие:

Перепишите ваш запрос SELECT INTO, так чтобы он вернул одну строку.

totn Oracle Error Messages


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

Description

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

  • ORA-01422: exact fetch returns more than requested number of rows

Cause

You tried to execute a SELECT INTO statement and more than one row was returned.

Resolution

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

Option #1

Rewrite your SELECT INTO statement so that only one row is returned.

Option #2

Replace your SELECT INTO statement with a cursor.

For example, if you tried to execute the following SQL statement:

SELECT supplier_id
INTO cnumber
FROM suppliers
WHERE supplier_name = 'IBM';

And there was more than one record in the suppliers table with the supplier_name of IBM, you would receive the ORA-01422 error message.

In this case, it might be more prudent to create a cursor and retrieve each row if you are unsure of how many records you might retrieve.

In my previous articles, I have given the proper idea of different oracle errors, which are frequently come. In this article, I will try to explain another common error, which has been searched on google approximately 10 k times per month. ORA-01422 is another simple error, which is commonly come in database when select into statement when it retrieves more than one row. All oracle errors are categorized in to two types one is network and memory issues and other are syntax errors come due to bad syntax. ORA-01422 is user-initiated mistake resulting from either a typo or a misunderstanding of how Oracle functions may work.

Cause and resolution of this error:

The ORA-01422 error is most common error, which will come because of the multiple reasons .The main reason of this error, is ‘SELECT INTO’ statement. Oracle has one important inbuilt error named ‘TOO_MANY_ROWS’ error.

ORA-01422

1.More than requested rows in “Select into”:

If ‘Select Into’ statement returns more than one rows in variable then this error will come. The error says fetch returns more than requested number of rows means ‘Exact Fetch’ will return ‘More than one row’. The basic problem will come from ‘Select Into’ statement from oracle, which will return more than one rows. The select statement will fetch the record from multiple databases and multiple tables and it will store into variable. The Oracle engine will fetch more than one record for single specified row. The ORA-01422 error will trigger when PLSQL engine returns multiple rows of data. The select into statement has default setting, which is designed to retrieve one row, but when it retrieves more than one rows, the ORA-01422 error will trigger.

Consider following real life example:

If table named ‘test_error’ has more than one records and user tries to fetch all records in to one variable this error will come.

Procedure :

DECLARE

v_test VARCHAR2(30);

BEGIN

SELECT roll_no INTO v_test FROM test_error;    —-Error statement

end;

Output:

Error report:

ORA-01422: exact fetch returns more than requested number of rows

ORA-06512: at line 4

01422. 00000 –  “exact fetch returns more than requested number of rows”

*Cause:    The number specified in exact fetch is less than the rows returned.

*Action:   Rewrite the query or change number of rows requested

Resolution of this error:

Handle the exception:

Just make the small change in the specified code and write the exception block for the same.

Procedure :

DECLARE

V_SRNUM VARCHAR2(20);

DECLARE

v_test VARCHAR2(30);

BEGIN

SELECT roll_no INTO v_test FROM test_error;

exception WHEN too_many_rows THEN

dbms_output.put_line(‘Errors fetching are more than one’);

end;

The above procedure will handle the error and anonyms block will complete successfully.So if this kind of error will occure handle user defined exception named ‘TOO_MANY_ROWS’.

2. Add cursor with loop:

There are many primitive adjustments to resolve this error. The approach needs to be chosen by the user dependent on the database tables and scenarios. The error will occur because of multiple rows are returning so user will change the code by adding the cursor.

Therefore, the above procedure will be:

Declare

v_test VARCHAR2(30);

begin

for c in (SELECT roll_no INTO v_test FROM test_error)

loop

v_test := c.roll_no;

end loop;

end;

3. Recommend to use aggregate function:

This error will come because of multiple rows selection. Therefore, as per requirement if user uses the aggregate function like sum, count then it will fetch only one row.

Therefore, the above procedure will be:

DECLARE

v_test VARCHAR2(30);

BEGIN

SELECT count(roll_no) INTO v_test FROM test_error;    —-Error statement

end;

4. Use of bulk collect:

This will pull more rows and variables but in a concise manner. However, be wary of using BULK COLLECT excessively as it can use a great deal of memory.

So there are different ways to deal with this error, my best recommendation is to use the cursor for fetching more than one rows and processing it.

I am a newbie in writing PL/SQL. I have this small code, but unable to print out the output due to the subject error.

declare
output_tour_id varchar(4000);

begin
dbms_output.enable;

for r in 
(
SELECT TOUR_ID FROM "/DSD/HH_RADELHD"
VERSIONS BETWEEN TIMESTAMP TO_TIMESTAMP('2015-04-02 18:00:00','YYYY-MM-DD    HH24:MI:SS')
AND TO_TIMESTAMP('2015-04-02 18:30:00','YYYY-MM-DD HH24:MI:SS')
WHERE VERSIONS_OPERATION = 'D'
group by VERSIONS_STARTTIME, CLIENT, TOUR_ID
) 

Loop
@/tmp/get.sql r.tour_id;
DBMS_OUTPUT.PUT_LINE (output_tour_id);
end loop;
end;
/

I get this error after executing:

old  30: WHERE CLIENT = 100 and TOUR_ID = &1;
new  30: WHERE CLIENT = 100 and TOUR_ID = r.tour_id;
'100','100002039690','000001','0001398563','0050543675','10','C170','20150402070750','CET','1',' ','10',' ','91597','20150330',' ',
declare
*
ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at line 13

Your inputs would be highly appreciated. Thank you in advance.

How do I make my code execute properly?

Возможно, вам также будет интересно:

  • Ora 01041 внутренняя ошибка hostdef расширение не существует
  • Ora 01036 illegal variable name number ошибка
  • Ora 01033 ошибка как исправить
  • Ora 01031 insufficient privileges ошибка
  • Ora 01012 not logged on ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

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