how handle table or view does not exist exception? - sql

I have a set of table names, let say 150. Each table have mail_id column, now I want to search one mail_id in all of the table. For that I wrote one Plsql block. When I loop through the set of table some tables do not exists so it raises an exception. I have exception handling block to handle that exception. Now I want to loop entire table even though it raise an exception? Any idea? Actually my block didn't handle that particular exception!
declare
my_mail_id varchar2(50):='xyaksj#jsm.com';
tmp_table varchar2(125);
type varchar_collector is table of varchar2(255);
var varchar_collector;
table_does_not_exist exception;
PRAGMA EXCEPTION_INIT(table_does_not_exist, -00942);
begin
for cntr in (select table_name from user_tables)
loop
tmp_table:=cntr.table_name;
dbms_output.put_line(tmp_table);
for mail in (select email_address from tmp_table where lower(email_address) like '%my_mail_id%' )
loop
dbms_output.put_line(tmp_table);
end loop;
end loop;
exception
when no_data_found then
dbms_output.put_line('email address not found');
WHEN table_does_not_exist then
dbms_output.put_line('table dose not exists');
WHEN OTHERS THEN
--raise_application_error(-20101, 'Expecting at least 1000 tables');
IF (SQLCODE = -942) THEN
--DBMS_Output.Put_Line (SQLERRM);
DBMS_Output.Put_Line ('in exception');--this exception not handled
ELSE
RAISE;
END IF;
end;

Just handle your exceptions in anonymous block inside the loop.
DECLARE
my_mail_id VARCHAR2(50) := 'xyaksj#jsm.com';
tmp_table VARCHAR2(125);
TYPE varchar_collector IS TABLE OF VARCHAR2(255);
var varchar_collector;
table_does_not_exist EXCEPTION;
PRAGMA EXCEPTION_INIT(table_does_not_exist, -00942);
BEGIN
FOR cntr IN (SELECT table_name FROM user_tables)
LOOP
BEGIN
tmp_table := cntr.table_name;
dbms_output.put_line(tmp_table);
FOR mail IN (SELECT email_address
FROM tmp_table
WHERE lower(email_address) LIKE '%my_mail_id%')
LOOP
dbms_output.put_line(tmp_table);
END LOOP;
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('email address not found');
WHEN table_does_not_exist THEN
dbms_output.put_line('table dose not exists');
WHEN OTHERS THEN
--raise_application_error(-20101, 'Expecting at least 1000 tables');
IF (SQLCODE = -942)
THEN
--DBMS_Output.Put_Line (SQLERRM);
DBMS_Output.Put_Line('in exception'); --this exception not handled
ELSE
RAISE;
END IF;
END;
END LOOP;
END;

If you're selecting from user_tables and finding that some of them do not exist then you're probably trying to query tables that are in the recycle bin (their names begin BIN$).
If so, change your query to:
select table_name
from user_tables
where dropped = 'NO';
You should replace your second cursor with a call to execute immediate also, constructing the query by concatenating in the table_name not just using a variable as the table name, and you might as well construct the query as:
select count(*)
from table_name
where lower(email_address) like '%my_mail_id%'
and rownum = 1;
That way you'll retrieve a single record that is either 0 or 1 to indicate whether the email address was found, and no need for error handling.

try below code...
DECLARE
foo BOOLEAN;
BEGIN
FOR i IN 1..10 LOOP
IF foo THEN
GOTO end_loop;
END IF;
<<end_loop>> -- not allowed unless an executable statement follows
NULL; -- add NULL statement to avoid error
END LOOP; -- raises an error without the previous NULL
END;

Related

if-else condition not working correctly in PL/SQL

I am writing a procedure to delete department from a table. It takes depatment id as argument and delete the department with given id. but it is not working correctly.When i didnot use EXCEPTION, it only give output when gien department id is present in table but if the id is not present in table it throw error. When i use exception, It did not check the if else condition.
Here is my procedure
CREATE OR REPLACE PROCEDURE del_job(j_id number) IS
jj_id bb_department.iddepartment%type;
BEGIN
SELECT IDDEPARTMENT
INTO jj_id
FROM BB_DEPARTMENT
WHERE IDDEPARTMENT=j_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
jj_id := NULL;
IF (jj_id=j_id) THEN
DELETE FROM BB_DEPARTMENT
WHERE IDDEPARTMENT=j_id;
dbms_output.put_line ('Job Deleted');
ELSIF(jj_id=0) THEN
dbms_output.put_line ('No Job Deleted');
END IF;
END;
/
Your indentation seems to imply that you want your if statement to be part of the normal flow rather than part of the exception block. But your actual code has the if statement in the exception handler. Since you're assigning a null to jj_id in the exception handler before running the if statement and null is never equal to nor unequal to any value, neither your if nor your elsif clause can ever be true so neither dbms_output call will be made.
Assuming your indentation shows your actual intent, my guess is that you want a nested PL/SQL block for the select statement and exception handler.
CREATE OR REPLACE PROCEDURE del_job(j_id number) IS
jj_id bb_department.iddepartment%type;
BEGIN
BEGIN
SELECT IDDEPARTMENT
INTO jj_id
FROM BB_DEPARTMENT
WHERE IDDEPARTMENT=j_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
jj_id := NULL;
END;
IF (jj_id=j_id) THEN
DELETE FROM BB_DEPARTMENT
WHERE IDDEPARTMENT=j_id;
dbms_output.put_line ('Job Deleted');
ELSIF(jj_id=0) THEN
dbms_output.put_line ('No Job Deleted');
END IF;
END;
/
You are making things overly difficult. DELETE sets sql%rowcount to the number of rows processed. So there is no need to select the department; just delete the appropriate id. If you want a confirmation message then test sql%rowcount. If the row was deleted it will contain 1 (or greater), if the id did not exist it will contain 0. Print the appropriate message.
create or replace procedure del_job(j_id number) is
begin
delete
from bb_department
where iddepartment=j_id;
if sql%rowcount > 0 then
dbms_output.put_line ('Job Deleted');
else
dbms_output.put_line ('No Job Deleted');
end if;
end del_job;
/

Implicit cursor and NO_DATA_FOUND exception

I have the following PL/SQL code:
BEGIN
FOR c IN (SELECT ...) LOOP
<code1>;
END LOOP;
<code2>;
EXCEPTION WHEN NO_DATA_FOUND THEN
NULL;
END;
This code should run code1 multiple times within a loop and upon finishing this loop code2 should be executed. Otherwise if SELECT query does not find data then I expect this should raise an exception and overstep code2, but this is not happening. Why?
NO_DATA_FOUND is thrown by statements that must return exactly one row but do not find a matching row, e.g.
DECLARE x NUMBER;
BEGIN
SELECT foo INTO x FROM bar WHERE xyz='abc';
EXCEPTION
WHEN NO_DATA_FOUND THEN
...
END;
In your case, you could do the following:
DECLARE foundSomething BOOLEAN := FALSE;
BEGIN
FOR c IN (SELECT ...) LOOP
foundSomething := TRUE;
<code1>;
END LOOP;
IF NOT foundSomething THEN
NULL; -- handle the situation
ELSE
<code2>;
END IF;
END;
No, that's not what is supposed to happen.
If there is no data, then loop runs 0 times - i.e. it skips code1 and executes code2.
You can define explicit cursors and do the checks for data unavailability like this:
DECLARE
cursor cur is select 1 a from dual where 1 = 1;
type tab is table of cur%rowtype;
v tab;
BEGIN
open cur;
loop
fetch cur bulk collect into v;
if v.count = 0 then
raise no_data_found;
end if;
dbms_output.put_line('Code1');
end loop;
close cur;
dbms_output.put_line('Code2');
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line('Error');
END;
/
You can easily extends this code to do other things such as divide fetch into batches etc.

Getting failed id's from for all save exceptions

I am trying to update salary of employees using forall. Whenever any error occurs while updating I need to save for which employee id error has occurred.
But it gives following error while compiling
Error(14,24): PLS-00201: identifier 'INDX' must be declared
Below is my code
PROCEDURE PROC1 (V_EMP_ID DBMS_SQL.NUMBER_TABLE)
IS
lv_error_string VARCHAR2(4000);
BEGIN
FORALL INDX IN V_EMP_ID.FIRST..V_EMP_ID.LAST SAVE EXCEPTIONS
EXECUTE IMMEDIATE 'UPDATE EMPLOYEES SET SALARY=SALARY+10000 WHERE EMP_ID=:1'
USING V_EMP_ID(INDX);
EXCEPTION
WHEN OTHERS
THEN
FOR J IN 1 .. SQL%BULK_EXCEPTIONS.COUNT
LOOP
lv_error_string:=lv_error_string
||sqlerrm (-sql%bulk_exceptions(j).error_code)
|| ' for'||V_EMP_ID(INDX);
END LOOP;
END;
Use this: The error is that in exception block you are trying to access a loop variable that is being used in begin block.
So your || ' for'||V_EMP_ID(INDX); should be || ' for'||V_EMP_ID(J);
CREATE OR REPLACE PROCEDURE PROC1 (V_EMP_ID DBMS_SQL.NUMBER_TABLE)
IS
lv_error_string VARCHAR2(4000);
BEGIN
FORALL INDX IN V_EMP_ID.FIRST..V_EMP_ID.LAST SAVE EXCEPTIONS
EXECUTE IMMEDIATE 'UPDATE EMPLOYEES SET SALARY=SALARY+10000 WHERE EMP_ID=:1'
USING V_EMP_ID(INDX);
EXCEPTION
WHEN OTHERS
THEN
FOR J IN 1 .. SQL%BULK_EXCEPTIONS.COUNT
LOOP
lv_error_string:=lv_error_string
||sqlerrm (-sql%bulk_exceptions(j).error_code)
|| ' for'||V_EMP_ID(J);
END LOOP;
END;
Not sure why you use Execute Immediate when you can easily do as below:
CREATE OR REPLACE PROCEDURE PROC1 (V_EMP_ID DBMS_SQL.NUMBER_TABLE)
IS
lv_error_string VARCHAR2(4000);
BEGIN
FORALL INDX IN V_EMP_ID.FIRST..V_EMP_ID.LAST SAVE EXCEPTIONS
UPDATE EMPLOYEES
SET SALARY=SALARY+10000
WHERE EMP_ID= V_EMP_ID(INDX);
EXCEPTION
WHEN OTHERS
THEN
FOR J IN 1 .. SQL%BULK_EXCEPTIONS.COUNT
LOOP
lv_error_string:=lv_error_string
||sqlerrm (-sql%bulk_exceptions(j).error_code)
|| ' for'||V_EMP_ID(J);
END LOOP;
END;
I would suggest to go with a single DML statement. And yes DML error loggins is possible.Hope this helps
--Creating a error log table
BEGIN
DBMS_ERRLOG.create_error_log (dml_table_name => 'EMPLOYEES');
END;
/
--ERR$_EMPLOYEES --> Errro table created
--Insertion with erroreous record
UPDATE EMPLOYEES
SET SALARY = SALARY + 10000
where EMP_ID in (<EMP_ID COLLECTION array
OR simple EMP_IDs>) LOG ERRORS
INTO ERR$_EMPLOYEES ('UPDATE') REJECT LIMIT UNLIMITED;
--Error will be logged into ERR$_EMPLOYEES table

Need to put TRY - CATCH in oracle stored procedure

I have created SP for creating unique index on multiple tables.
Now i need to create Try-catch (exception handling) for this, like incase index not created this should be catch ....
For example i have 200 tables and only 1 tables is giving error, Then 199 tables should be created with index and catch log have that one error-ed tables name.
Please help .
DECLARE
CURSOR C_TABLE IS
SELECT INPUT_TABLE,HISTORY_TABLE FROM FUNCTIONS WHERE TARGET_SYS IN ('ABC','DEC') AND ACTIVE_FLAG='Y';
SQL_CREATE_INX VARCHAR2(200);
SQL_TABLE_NAME VARCHAR2(200);
BEGIN
-- INPUT TABLE
FOR I IN C_TABLE
LOOP
SQL_CREATE_INX:='CREATE UNIQUE INDEX CLM1.AUDIT_SUB_SITE_INX ON '||I.INPUT_TABLE||' (AUDIT_NBR , SUB_AUDIT_NBR , STATE) ';
SQL_TABLE_NAME:=I.INPUT_TABLE;
EXECUTE IMMEDIATE SQL_CREATE_INX;
DBMS_OUTPUT.PUT_LINE('INDEX DONE : '||SQL_TABLE_NAME);
END LOOP;
DBMS_OUTPUT.PUT_LINE('INDEXES CREATED FOR ALL INPUT TABLES');
-- OUTPUT TABLE
FOR H IN C_TABLE
LOOP
SQL_CREATE_INX:='CREATE UNIQUE INDEX CLM1.AUDIT_SUB_SITE_INX ON '||H.HISTORY_TABLE||' (AUDIT_NBR , SUB_AUDIT_NBR , STATE) ';
SQL_TABLE_NAME:=H.HISTORY_TABLE;
EXECUTE IMMEDIATE SQL_CREATE_INX;
DBMS_OUTPUT.PUT_LINE('INDEX DONE : '||SQL_TABLE_NAME);
END LOOP;
DBMS_OUTPUT.PUT_LINE('INDEXES CREATED FOR ALL OUTPUT TABLES');
END;
You need to enclose all EXEC IMMEDIATE into BEGIN .. END
FOR (.... )
LOOP
/*
* Other Statements
*/
BEGIN /* try */
EXECUTE IMMEDIATE SQL_CREATE_INX;
/* If it is success the below output happens */
DBMS_OUTPUT.PUT_LINE('INDEX DONE : '||SQL_TABLE_NAME);
EXCEPTION /*catch */
/* It is like catch(Exception e) All execeptions go here..*/
WHEN OTHERS THEN
/* Log your error message here.. SQLERRM has it..*/
DBMS_OUTPUT.PUT_LINE('DDL FAILED FOR '||SQL_TABLE_NAME||'::FAILED WITH ERROR::'||SQLERRM);
END;
/*
* Other Statements
*/
END LOOP;
In oracle handling of exceptions is like below
Declare
--declaration
BEGIN
--executable_section
EXCEPTION
WHEN exception_name1 THEN
[statements]
WHEN exception_name2 THEN
[statements]
WHEN exception_name_n THEN
[statements]
WHEN OTHERS THEN
[statements]
END
By editing your procedure with exception block is below
DECLARE
CURSOR C_TABLE IS
SELECT INPUT_TABLE,HISTORY_TABLE FROM FUNCTIONS WHERE TARGET_SYS IN ('ABC','DEC') AND ACTIVE_FLAG='Y';
var1 number;
var2 number;
SQL_CREATE_INX VARCHAR2(200);
SQL_TABLE_NAME VARCHAR2(200);
BEGIN
-- INPUT TABLE
FOR I IN C_TABLE
LOOP
select 1 into var1 from user_tables where table_name=upper(i.INPUT_TABLE)
if var1=1
then
SQL_CREATE_INX:='CREATE UNIQUE INDEX CLM1.AUDIT_SUB_SITE_INX ON '||I.INPUT_TABLE||' (AUDIT_NBR , SUB_AUDIT_NBR , STATE) ';
SQL_TABLE_NAME:=I.INPUT_TABLE;
EXECUTE IMMEDIATE SQL_CREATE_INX;
DBMS_OUTPUT.PUT_LINE('INDEX DONE : '||SQL_TABLE_NAME);
end if;
END LOOP;
DBMS_OUTPUT.PUT_LINE('INDEXES CREATED FOR ALL INPUT TABLES');
-- OUTPUT TABLE
FOR H IN C_TABLE
LOOP
select 1 into var2 from user_tables where table_name=upper(h.HISTORY_TABLE)
if var2=1
then
SQL_CREATE_INX:='CREATE UNIQUE INDEX CLM1.AUDIT_SUB_SITE_INX ON '||H.HISTORY_TABLE||' (AUDIT_NBR , SUB_AUDIT_NBR , STATE) ';
SQL_TABLE_NAME:=H.HISTORY_TABLE;
EXECUTE IMMEDIATE SQL_CREATE_INX;
DBMS_OUTPUT.PUT_LINE('INDEX DONE : '||SQL_TABLE_NAME);
end if;
END LOOP;
DBMS_OUTPUT.PUT_LINE('INDEXES CREATED FOR ALL OUTPUT TABLES');
exception
WHEN OTHERS THEN
Dbms_output.put_line(sqlerrm ||' error occured with this error code '||SQLCODE);
END;
Some Predefined exceptions in oracle and edit the plsql block with your exception name.

How to create a procedure in an oracle sql script and use it inside the script?

I want to create a script for my oracle DB, which drops tables. If the table does not exist, the script won't exit as fail, just print a text: "does not exists".
The script is the following:
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE mytable';
DBMS_Output.Put_Line(' table dropped');
EXCEPTION WHEN OTHERS THEN
IF SQLCODE = -942 THEN
DBMS_Output.Put_Line(' table not exists');
ELSE
DBMS_Output.Put_Line(' Unknown exception while dropping table');
RAISE;
END IF;
END;
I want to drop a lot of table in one script, and I don't want to write these lines more than once.
Is there any way, to write it to a procedure or function which gets a parameter (the name of the table), and call this procedure in that script?
Maybe something like this:
drop_table_procedure('mytableA');
drop_table_procedure('mytableB');
Or maybe a procedure, which gets an undefined size list (like in java: String ... table names):
drop_tables_procedure('mytableA','mytableB');
Please give me some examples.
Thanks!
Yes, you can declare a "temporary" procedure in an anonymous PL/SQL block:
DECLARE
PROCEDURE drop_if_exists(p_tablename VARCHAR)
IS
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE '||p_tablename;
DBMS_Output.Put_Line(' table dropped');
EXCEPTION WHEN OTHERS THEN
IF SQLCODE = -942 THEN
DBMS_Output.Put_Line(' table not exists');
ELSE
DBMS_Output.Put_Line(' Unknown exception while dropping table');
RAISE;
END IF;
END;
BEGIN
drop_if_exists('TABLE_1');
drop_if_exists('TABLE_2');
END;
/
in execute immediate you need add name of database object.
here's the script
create table t1 (col1 int);
create table t2 (col1 int);
create procedure drop_my_table(av_name varchar2)
as
begin
EXECUTE IMMEDIATE 'DROP TABLE '||av_name;
DBMS_Output.Put_Line(' table dropped');
EXCEPTION WHEN OTHERS THEN
IF SQLCODE = -942 THEN
DBMS_Output.Put_Line(' table not exists');
ELSE
DBMS_Output.Put_Line(' Unknown exception while dropping table');
RAISE;
END IF;
end drop_my_table;
declare
type array_t is varray(2) of varchar2(30);
atbls array_t := array_t('t1', 't2');
begin
for i in 1..atbls.count loop
drop_my_table(atbls(i));
end loop;
end;
You can use below one also
create or replace PROCEDURE drop_if_exists(p_tablename in VARCHAR)
IS
v_var1 number;
begin
select 1 into v_var1 from user_tables where table_name=upper(p_tablename);
if v_var1=1
then
EXECUTE IMMEDIATE 'DROP TABLE '||p_tablename;
DBMS_Output.Put_Line(' table dropped');
else
DBMS_Output.Put_Line(' table not exist');
end if;
exception
when others then
DBMS_Output.Put_Line(' Unknown exception while dropping table');
RAISE;
end;
Call procedure
begin
drop_if_exists('emp');
end;
/