Oracle: If Table Exists
Run this PL/SQL block to check table existence via all_tables
. Swap YOUR_TABLE
and YOUR_SCHEMA
for your values. You get a quick, direct existence check without having to harness exceptions.
Handling different types of objects
Not only tables, you might need to check the existence of other DB objects as well. Here's how to do this dynamically:
Remember to capitalize the object name and type for consistency and apply UPPER
when dealing with user input!
Dealing with conditional drops
Prior to Oracle 23c, an error handling routine was crucial to conditionally drop tables. Now, IF EXISTS
simplifies this process. But, if you're on older versions or when IF EXISTS
is unavailable, use this:
This routine checks for SQLCODE -942, which flags non-existent tables. Modify to suit other objects and SQLCODEs.
Watch out for the CASCADE!
When dropping objects, be extra cautious with CASCADE
. It might wipe more than you asked for!
For scheduled jobs, always use DBMS_SCHEDULER.drop_job
, managing exceptions like the table drop example. This avoidance action ensures no jobs linger in the shadows.
Dabble with dynamic SQL
Sometimes you need to create or alter tables dynamically.
Add EXECUTE IMMEDIATE
with a SELECT ... INTO
for dynamic table creation:
Remember, error handling is a must in dynamic SQL!
Halt scripts on error
Need your script to stop at the first sign of trouble? Here's a command for that:
This command will stop your script like a traffic light at any SQL error, leaving the error to the calling environment.
Was this article helpful?