PL-SQL Stored Procedure : DROP_IF_EXISTS

PL-SQL Stored Procedure : DROP_IF_EXISTS

Hi ,

While developing ETL processes with PL-SQL we use “drop-create” for loading data to temp tables. Before creating temp table, we need to drop if it is exists in the database. If you try directly drop the table, and the table did not exists yet , then you will get “ORA-00942table or view does not exist” error.

Here is a PL-SQL procedure to drop it so you can create it without any error;

CREATE OR REPLACE PROCEDURE TECHBROS.DROP_IF_EXISTS (p_table_name IN VARCHAR2) IS
v_control NUMBER(1);
BEGIN
SELECT COUNT(1) 
  INTO v_control 
  FROM user_tables a
  WHERE UPPER(a.table_name) = UPPER(p_table_name); 
IF v_control >= 1 THEN 
  EXECUTE IMMEDIATE('DROP TABLE '||p_table_name); 
END IF;
EXCEPTION WHEN OTHERS THEN NULL;
END drop_if_exists; 

For run the procedure;

call TECHBROS.DROP_IF_EXISTS('TEMP_TABLE_TO_DELETE');
Gunes INAL

2 Comments

Marcus Posted on18:03 - 10 November 2019

Do not use this statement to remove a procedure that is part of a package. Instead, either drop the entire package using the DROP PACKAGE Statement, or redefine the package without the procedure using the CREATE PACKAGE Statement with the When you drop a procedure, the database invalidates any local objects that depend upon the dropped procedure. If you subsequently reference one of these objects, then the database tries to recompile the object and returns an error message if you have not re-created the dropped procedure.

Isabella Posted on22:32 - 20 November 2019

Warning: the check if the stored procedure exists function will always return exists , no matter what function name you put in (for T-SQL). It is an unreliable check. Ryan Battistone Sep 11 ’18 at 21:36 A better alternative: IF EXISTS(SELECT 1 FROM sys.procedures WHERE name = name_of_table_as_seen_in_sysprocedures ) BEGIN select -1 as status END Ryan Battistone Sep 11 ’18 at 21:41