5
DROP TABLE IF EXISTS Pose ;

results in the error

Error code -1, SQL state 42X01: Syntax error: Encountered "EXISTS" at line 1, column 15. 

I'm running this from inside NetBeans 7.3 using the default Derby sample db.

Jag
  • 1,840
  • 1
  • 17
  • 25
  • 1
    Is this mysql or apache derby? They are not the same thing and don't support exactly the same SQL language. – greg-449 Sep 03 '13 at 16:13
  • I was unaware! This is apache derby. Does it support some variant of if exists? – Jag Sep 03 '13 at 17:09

5 Answers5

8

Derby does not currently support IF EXISTS

greg-449
  • 109,219
  • 232
  • 102
  • 145
2

The MySQL 6.0 syntax for declaring a table is this:

CREATE TABLE [IF NOT EXISTS] tableName ...

and the MySQL syntax for removing a table is this:

DROP TABLE [IF EXISTS] tableName ...

These clauses are MySQL extensions which are not part of the ANSI/ISO SQL Standard. This functionality may be peculiar to MySQL: I can't find anything similar documented for Derby, Postgres, Oracle, or DB2.

2

Are you trying to create a table? If yes, this is what you should do:

 public void createTables() throws SQLException {

    Statement statement = getConnection().createStatement();
    System.out.println("Checking database for table");
    DatabaseMetaData databaseMetadata = getConnection().getMetaData();
    ResultSet resultSet = databaseMetadata.getTables(null, null, "PATIENT", null);
    if (resultSet.next()) {
       System.out.println("TABLE ALREADY EXISTS");
    } else {
        //language=MySQL
        statement.execute("CREATE TABLE Patient (" +
                "CardNumber CHAR(10) NOT NULL PRIMARY KEY, " +
                " FirstName CHAR(50)," +
                " MiddleName CHAR(50)," +
                " LastName CHAR(50) )");
    }
}

Remember to use all caps for the table name you pass into databaseMetadata.getTables(...)

Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132
1

The best alternative I can find is to query the system tables to see if the table exists.

select count(*) from sys.systables where tablename = 'YOUR_TABLE_NAME'"

I had a similar issue dropping stored procedures. They can be queried using this statement.

select count(*) from sys.sysaliases where alias = 'YOUR_STORED_PROCEDURE_NAME'

darrenmc
  • 1,721
  • 1
  • 19
  • 29
0

If someone is looking to drop and create a table in an sql file that is Run with Spring test framework, Check https://stackoverflow.com/a/47459214/3584693 for an answer that ensures that no exception is thrown when drop table is invoked when said table doesn't exist.

Deepak
  • 3,648
  • 1
  • 22
  • 17