Not handle no_data_found - oracle

I having emp table, in that there is no records. I used those table in SQL and PL/SQL block
SQL> BEGIN
2 FOR i IN (SELECT * FROM emp WHERE 1=2) -- emp table having no data
3 LOOP
4 dbms_output.put_line('Done');
5 END LOOP;
6 EXCEPTION
7 WHEN no_data_found THEN
8 dbms_output.put_line('No such value');
9 END;
10 /
PL/SQL procedure successfully completed. -- it shows completed, instead of handling no_data_found
SQL> SELECT * FROM emp
2 WHERE 1=2;
no rows selected -- but here it show no rows selected
In pl/sql block, instead of handling no_data_found it shows pl/sql successfully completed
But in SQL statement it shows no rows selected.
I want to know what is actually happened in plsql and sql statement?

The code between the LOOP and END LOOP clauses is executed once per row in the cursor. Your cursor returns zero rows so it never gets executed.
The cursor loops gracefully handles the empty result by design, because coming to the end of the result set is expected, even when it is zero rows. So it does not hurls the NO_DATA_FOUND exception.
That's why you see no messages.
On the other hand the SQL statement expects a query to return rows and raises no data found when none are returned. However, you are executing the SQL statement in a client - SQL*Plus in this case - which handles this outcome and displays a message.
If you want your PL/SQL to exhibit the same behaviour, don't use a cursor loop:
declare
l_emp_rec emp%rowtype;
begin
select *
into l_emp_rec
from emp
where 1 = 2; -- emp table having no data
dbms_output.put_line('Done');
exception
when no_data_found then
dbms_output.put_line('No such value');
end;
/

Related

ORA-00001: unique constraint violated when inserting 0 rows

I am trying to insert 0 rows into a table that has a unique constraint and I am getting ORA-00001: unique constraint violated...
Below is the PL/SQL block I've used to hopefully capture the issue well
declare
l_cnt number;
begin
set transaction isolation level serializable;
select count(*) into l_cnt from test_view;
dbms_output.put_line('count = ' || to_char(l_cnt));
insert into <table>(<columns>)
select <columns> from test_view
log errors ('run1')
reject limit 0
;
dbms_output.put_line('success');
exception
when others then
dbms_output.put_line('ERRROR!');
dbms_output.put_line(sqlerrm);
rollback;
end;
/
This is the output
count = 0
ERRROR!
ORA-00001: unique constraint (<SCHEMA>.<CONSTRAINT>) violated
And sure enough, there is a record in the ERR$_<table> table...
If I add where 1 = 0 to the in the insert statement, everything works, nothing is inserted.
I still don't believe what I am seeing :)
Oracle Database 12c Standard Edition Release 12.2.0.1.0 - 64bit Production
Update 1
Below sample without using count(*) on the view as this could lead to a different query plan that selecting all required values for the insert.
declare
l_cnt number;
begin
set transaction isolation level serializable;
insert into testx_table
select * from testx_view d;
select count(*) into l_cnt from testx_table;
dbms_output.put_line('count = ' || to_char(l_cnt));
insert into <table>(<columns>)
select * from testx_view d
log errors ('run2')
reject limit 0;
dbms_output.put_line('success');
exception
when others then
dbms_output.put_line('ERRROR!');
dbms_output.put_line(sqlerrm);
rollback;
end;
/
UPDATE 2
I was able to reproduce the behaviour.
CREATE TABLE A(ID NUMBER PRIMARY KEY)
/
CREATE FUNCTION F(ID_ NUMBER) RETURN NUMBER
AS
L_ID NUMBER;
BEGIN
SELECT ID INTO L_ID FROM A WHERE ID = ID_;
RETURN L_ID;
EXCEPTION
WHEN OTHERS THEN
RETURN NULL;
END;
/
BEGIN
DBMS_ERRLOG.CREATE_ERROR_LOG('A');
END;
/
BEGIN
INSERT INTO A VALUES (1);
INSERT INTO A SELECT 1 FROM DUAL WHERE F(1) IS NULL
LOG ERRORS INTO ERR$_A;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
/
SELECT * FROM ERR$_A
/
sqlfiddle
And it all boils down to querying table that is being modified from within the function. The functions throws the ORA-04091: table A is mutating, trigger/function may not see it but the code catches all exceptions and returns null.
Obviously, selecting from table that's mutating is a nono and must be fixed.
And I am quite angry as I cannot count the number of times I told my collegues to stop using exception when others then return null. This is again an example where it completely masked the issue and I've spent the whole day deubgging it.
Select returned 0 rows, that was ok.
However when inserting rows to table, we were actually querying the same table through a function. The function returned ORA-04091: table A is mutating, trigger/function may not see it but it was catched in an exception block and null was returned. This caused the query to return rows...
Never use exception when others then return null!!!

Oracle pl/sql Procedure to update table - exception handling

This is my first query on PL/SQL and I did spend an hour trying to find answers on the net, anyway - here it goes.
I'm writing a procedure to update a table and it all works fine, however when I typed in to update a job_id that doesn't exist, I expected my exception handling to tell me that the job_id is invalid, however I got no error message.
My code is as follows:
CREATE OR REPLACE PROCEDURE UPD_JOB(p_job_id jobs.job_id%TYPE, p_jobnew jobs.job_title%TYPE)
IS
BEGIN
UPDATE JOBS SET job_title =p_jobnew WHERE JOB_ID = p_job_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('No rows have been updated');
END;
/
I then tried to update a job_id that I knew didn't exist to see if the exception works by typing the following
EXECUTE UPD_JOB('ABCXXX','WILL FAIL');
From "Handling PL/SQL Errors":
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. SQL aggregate functions such as AVG and SUM always return a value or a null. So, a SELECT INTO statement that calls an aggregate function never raises NO_DATA_FOUND. The FETCH statement is expected to return no rows eventually, so when that happens, no exception is raised.
You're not using a statement that would cause a NO_DATA_FOUND exception to be raised.
Maybe you can use SQL%ROWCOUNT. From "Performing SQL Operations from PL/SQL":
To find out how many rows are affected by DML statements, you can check the value of SQL%ROWCOUNT...
CREATE OR REPLACE PROCEDURE UPD_JOB (p_job_id jobs.job_id%TYPE,
p_jobnew jobs.job_title%TYPE)
IS
BEGIN
UPDATE JOBS
SET job_title = p_jobnew
WHERE JOB_ID = p_job_id;
IF SQL%ROWCOUNT = 0 THEN
DBMS_OUTPUT.PUT_LINE('No rows have been updated');
END IF;
END;
/

PL/SQL process: issue with wording

I am trying to create a page process in Oracle APEX 4.1. Specifically, When a button on this page is process submitting the page, I want this PL/SQL query to work. I don't have much of an understanding of PL/SQL and am looking to find out how to figure this issue out.
What I want the query to do:
I would like this page process to loop through each row in the EMPLOYEE table that I have in a database for APEX. For each row, I want to move the username, group and password into their own variables, and then to create an APEX user using the APEX_UTIL_CREATE_USER process. I want this to be done with every employee in the table.
I don't know specifically what is wrong with this PL/SQL, as I have never had to use it before. I would greatly appreciate any help anyone can give me with this. I will show the query and the error message below.
PL/SQL query:
PROCEDURE deploy_employee
(EMP_USERNAME IN EMPLOYEE)
IS
BEGIN
FOR indx IN NVL (EMP_USERNAME.FIRST, 0)
.. NVL (EMP_USERNAME.LAST, -1)
LOOP
emp_user EMPLOYEE.EMP_USERNAME%TYPE;
emp_pass EMPLOYEE.EMP_PASSWORD%TYPE;
emp_group EMPLOYEE.EMP_GROUP%TYPE;
BEGIN
BEGIN
select EMP_USERNAME into emp_user from EMPLOYEE;
select EMP_PASSWORD into emp_pass from EMPLOYEE;
select EMP_GROUP into emp_group FROM EMPLOYEE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
emp_user := NULL;
emp_pass := NULL;
emp_group := NUL;
END;
APEX_UTIL.CREATE_USER(
p_user_name => emp_user,
p_web_password => emp_pass,
p_user_group => emp_gorup,
);
END;
END LOOP;
END deploy_employee;
Error message:
1 error has occurred ORA-06550: line 2, column 1: PLS-00103:
Encountered the symbol "PROCEDURE" when expecting one of the
following: ( begin case declare end exception exit for goto if loop
mod null pragma raise return select update while with <an identifier>
<a double-quoted delimited-identifier> <a bind variable> << continue
close current delete fetch lock insert open rollback savepoint set sql
execute commit forall merge pipe purge The symbol "declare" was
substituted for "PROCEDURE" to continue. ORA-065
The page number is 2.
Once again I would be greatly appreciative of any help I could gain.
There are multiple issues with your procedure.
You are missing the CREATE keyword, and that's the root cause for the compile time error. PLS-00103.
See the documentation for more details on CREATE PROCEDURE statement to create a standalone stored procedure or a call specification.
EMP_USERNAME IN EMPLOYEE
The data type declaration for the IN parameter is incorrect. You need to do it as:
EMP_USERNAME IN EMPLOYEE.EMP_USERNAME%TYPE
The FOR LOOP is syntactically incorrect.
FOR indx IN NVL (EMP_USERNAME.FIRST, 0) .. NVL (EMP_USERNAME.LAST, -1)
You could do it as:
SQL> CREATE OR REPLACE
2 PROCEDURE deploy_emp(
3 i_emp emp.empno%type)
4 IS
5 emp_user VARCHAR2(50);
6 BEGIN
7 FOR indx IN
8 (SELECT ename FROM emp
9 )
10 LOOP
11 BEGIN
12 BEGIN
13 SELECT ename INTO emp_user FROM emp WHERE empno = i_emp;
14 EXCEPTION
15 WHEN NO_DATA_FOUND THEN
16 emp_user := NULL;
17 END;
18 END;
19 END LOOP;
20 dbms_output.put_line(emp_user);
21 END deploy_emp;
22 /
Procedure created.
SQL> sho err
No errors.
Now, let's test it and see:
SQL> set serveroutput on
SQL> EXEC deploy_emp(7369);
SMITH
PL/SQL procedure successfully completed.
SQL>
use CREATE PROCEDURE to create a new stored procedure or EXEC <proc name> to execute it
If you whant do all this in a page process, you don't need to create procedure. Put this code in the source of your page process:
BEGIN
FOR indx IN (
select *
from EMPLOYEE
) LOOP
APEX_UTIL.CREATE_USER(
p_user_name => indx.EMP_USERNAME,
p_web_password => indx.EMP_PASSWORD,
p_user_group => indx.EMP_GROUP,
);
END LOOP;
END;

Further PL/SQL issues [duplicate]

I am trying to create a page process in Oracle APEX 4.1. Specifically, When a button on this page is process submitting the page, I want this PL/SQL query to work. I don't have much of an understanding of PL/SQL and am looking to find out how to figure this issue out.
What I want the query to do:
I would like this page process to loop through each row in the EMPLOYEE table that I have in a database for APEX. For each row, I want to move the username, group and password into their own variables, and then to create an APEX user using the APEX_UTIL_CREATE_USER process. I want this to be done with every employee in the table.
I don't know specifically what is wrong with this PL/SQL, as I have never had to use it before. I would greatly appreciate any help anyone can give me with this. I will show the query and the error message below.
PL/SQL query:
PROCEDURE deploy_employee
(EMP_USERNAME IN EMPLOYEE)
IS
BEGIN
FOR indx IN NVL (EMP_USERNAME.FIRST, 0)
.. NVL (EMP_USERNAME.LAST, -1)
LOOP
emp_user EMPLOYEE.EMP_USERNAME%TYPE;
emp_pass EMPLOYEE.EMP_PASSWORD%TYPE;
emp_group EMPLOYEE.EMP_GROUP%TYPE;
BEGIN
BEGIN
select EMP_USERNAME into emp_user from EMPLOYEE;
select EMP_PASSWORD into emp_pass from EMPLOYEE;
select EMP_GROUP into emp_group FROM EMPLOYEE;
EXCEPTION
WHEN NO_DATA_FOUND THEN
emp_user := NULL;
emp_pass := NULL;
emp_group := NUL;
END;
APEX_UTIL.CREATE_USER(
p_user_name => emp_user,
p_web_password => emp_pass,
p_user_group => emp_gorup,
);
END;
END LOOP;
END deploy_employee;
Error message:
1 error has occurred ORA-06550: line 2, column 1: PLS-00103:
Encountered the symbol "PROCEDURE" when expecting one of the
following: ( begin case declare end exception exit for goto if loop
mod null pragma raise return select update while with <an identifier>
<a double-quoted delimited-identifier> <a bind variable> << continue
close current delete fetch lock insert open rollback savepoint set sql
execute commit forall merge pipe purge The symbol "declare" was
substituted for "PROCEDURE" to continue. ORA-065
The page number is 2.
Once again I would be greatly appreciative of any help I could gain.
There are multiple issues with your procedure.
You are missing the CREATE keyword, and that's the root cause for the compile time error. PLS-00103.
See the documentation for more details on CREATE PROCEDURE statement to create a standalone stored procedure or a call specification.
EMP_USERNAME IN EMPLOYEE
The data type declaration for the IN parameter is incorrect. You need to do it as:
EMP_USERNAME IN EMPLOYEE.EMP_USERNAME%TYPE
The FOR LOOP is syntactically incorrect.
FOR indx IN NVL (EMP_USERNAME.FIRST, 0) .. NVL (EMP_USERNAME.LAST, -1)
You could do it as:
SQL> CREATE OR REPLACE
2 PROCEDURE deploy_emp(
3 i_emp emp.empno%type)
4 IS
5 emp_user VARCHAR2(50);
6 BEGIN
7 FOR indx IN
8 (SELECT ename FROM emp
9 )
10 LOOP
11 BEGIN
12 BEGIN
13 SELECT ename INTO emp_user FROM emp WHERE empno = i_emp;
14 EXCEPTION
15 WHEN NO_DATA_FOUND THEN
16 emp_user := NULL;
17 END;
18 END;
19 END LOOP;
20 dbms_output.put_line(emp_user);
21 END deploy_emp;
22 /
Procedure created.
SQL> sho err
No errors.
Now, let's test it and see:
SQL> set serveroutput on
SQL> EXEC deploy_emp(7369);
SMITH
PL/SQL procedure successfully completed.
SQL>
use CREATE PROCEDURE to create a new stored procedure or EXEC <proc name> to execute it
If you whant do all this in a page process, you don't need to create procedure. Put this code in the source of your page process:
BEGIN
FOR indx IN (
select *
from EMPLOYEE
) LOOP
APEX_UTIL.CREATE_USER(
p_user_name => indx.EMP_USERNAME,
p_web_password => indx.EMP_PASSWORD,
p_user_group => indx.EMP_GROUP,
);
END LOOP;
END;

Reasonable SELECT ... INTO Oracle solution for case of multiple OR no rows

I just want to SELECT values into variables from inside a procedure.
SELECT blah1,blah2 INTO var1_,var2_
FROM ...
Sometimes a large complex query will have no rows sometimes it will have more than one -- both cases lead to exceptions. I would love to replace the exception behavior with implicit behavior similiar to:
No rows = no value change, Multiple rows = use last
I can constrain the result set easily enough for the "multiple rows" case but "no rows" is much more difficult for situations where you can't use an aggregate function in the SELECT.
Is there any special workarounds or suggestions? Looking to avoid significantly rewriting queries or executing twice to get a rowcount before executing SELECT INTO.
Whats wrong with using an exception block?
create or replace
procedure p(v_job VARCHAR2) IS
v_ename VARCHAR2(255);
begin
select ename into v_ename
from (
select ename
from scott.emp
where job = v_job
order by v_ename desc )
where rownum = 1;
DBMS_OUTPUT.PUT_LINE('Found Rows Logic Here -> Found ' || v_ename);
EXCEPTION WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No Rows found logic here');
end;
SQL> begin
p('FOO');
p('CLERK');
end; 2 3 4
5 /
No Rows found logic here
Found Rows Logic Here -> Found SMITH
PL/SQL procedure successfully completed.
SQL>
You could use a for loop. A for loop would do nothing for no rows returned and would be applied to every row returned if there where multiples. You could adjust your select so that it only returns the last row.
begin
for ARow in (select *
from tableA ta
Where ta.value = ???) loop
-- do something to ARow
end loop;
end;

Resources