IF EXISTS not recognized in Derby

﹥>﹥吖頭↗ 提交于 2019-12-07 20:13:10

问题


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.


回答1:


Derby does not currently support IF EXISTS




回答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(...)




回答3:


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.




回答4:


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'




回答5:


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.



来源:https://stackoverflow.com/questions/18593019/if-exists-not-recognized-in-derby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!