7

Possible Duplicate:
Oracle: If Table Exists
Drop table if it exists

I'm trying to create this procedure but I get an error.

CREATE OR REPLACE PROCEDURE SP_VEXISTABLA(NOMBRE IN VARCHAR2)
IS
CANTIDAD NUMBER(3);
BEGIN
SELECT COUNT(*) INTO CANTIDAD FROM ALL_OBJECTS WHERE OBJECT_NAME = NOMBRE;
IF (CANTIDAD >0) THEN
    DROP TABLE NOMBRE;
END IF;
END;

The error is:

Error(8,1): PLS-00103: Encountered the symbol "END" when expecting one of the following: ( begin case declare exit for goto if loop mod null pragma raise return select update while with << continue close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe purge.

Do you know what am I doing wrong?

Community
  • 1
  • 1
Alejandro Bastidas
  • 1,382
  • 2
  • 20
  • 26
  • Which tool do you use to run this? – a_horse_with_no_name Jan 28 '13 at 15:01
  • Oracle sql developer Version 3.2.20.09 – Alejandro Bastidas Jan 28 '13 at 15:02
  • 3
    It's not allowed to use DDL statements (`DROP TABLE NOMBRE;` in this case ) inside a PL/SQL block. To execute a DDL statement inside a PL/SQL block you would have to use dynamic SQL: `execute immediate 'DROP TABLE NOMBRE';` for instance. – Nick Krasnov Jan 28 '13 at 15:04
  • 3
    You should be aware that by querying ALL_OBJECTS you might find an object that is neither a table nor in your own schema. If you only want to query for tables in your own schema then use USER_TABLES. Also, if TABLE_LOCK is "DISABLED" or DROPPED is "YES" then the drop will fail. – David Aldridge Jan 28 '13 at 15:25

3 Answers3

19

you'd need to change your procedure to:

CREATE OR REPLACE PROCEDURE SP_VEXISTABLA(NOMBRE IN VARCHAR2)
IS
CANTIDAD NUMBER(3);
BEGIN
SELECT COUNT(*) INTO CANTIDAD FROM USER_TABLES WHERE TABLE_NAME = NOMBRE;
IF (CANTIDAD >0) THEN
    execute immediate 'DROP TABLE ' || NOMBRE;
END IF;
END;
DazzaL
  • 21,110
  • 3
  • 45
  • 56
3

You cannot DROP tables in procedure using the DROP command. You need to use EXECUTE IMMEDIATE to run DDL commands in PL/SQL.

Ben
  • 50,172
  • 36
  • 122
  • 141
Art
  • 5,396
  • 1
  • 19
  • 22
1

It will not allow you use directly DDL statament inside the PLSQL Procedure. You need to use Execute Immediate statement in order to execute the DDL.

Use the code below:

CREATE OR REPLACE PROCEDURE SP_VEXISTABLA(Table_nameIN VARCHAR2)
IS
CANTIDAD integer;
BEGIN
   SELECT COUNT(*) INTO CANTIDAD FROM USER_TABLES WHERE TABLE_NAME = Table_name;
   DBMS_OUTPUT.PUT_LINE(CANTIDAD);
   IF (CANTIDAD >0) THEN
      DBMS_OUTPUT.PUT_LINE(Table_name);
      execute immediate 'DROP TABLE ' || Table_name;
   END IF;
END;
Eray Balkanli
  • 7,306
  • 10
  • 44
  • 74
user2001117
  • 3,575
  • 16
  • 18