How to Drop a table if exists using execute immediate in a PL/SQL Block

 

Safe Drop Table in PL/SQL

BEGIN EXECUTE IMMEDIATE 'DROP TABLE MAIN_SUB_LOC_NZ_BKP PURGE'; EXCEPTION WHEN OTHERS THEN IF SQLCODE = -942 THEN NULL; -- table does not exist, ignore ELSE RAISE; END IF; END; /

Explanation

  • EXECUTE IMMEDIATE → Required for DDL inside PL/SQL

  • -942 → ORA-00942 (table does not exist)

  • PURGE → Skips recycle bin


Better Version (Checking USER_TABLES First)

Cleaner and more controlled:

DECLARE v_count NUMBER; BEGIN SELECT COUNT(*) INTO v_count FROM user_tables WHERE table_name = 'MAIN_SUB_LOC_NZ_BKP'; IF v_count > 0 THEN EXECUTE IMMEDIATE 'DROP TABLE MAIN_SUB_LOC_NZ_BKP PURGE'; END IF; END; /

Post a Comment

And that's all there is to it!

If anyone has any other questions or requests for future How To posts, you can either ask them in the comments or email me. Please don't feel shy at all!

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

Previous Post Next Post