Java SQL Table Drop dropTableIfExists(String tableName, java.sql.Statement stmt)

Here you can find the source of dropTableIfExists(String tableName, java.sql.Statement stmt)

Description

mimic "DROP TABLE IF EXISTS ..."

License

Open Source License

Declaration

public static void dropTableIfExists(String tableName, java.sql.Statement stmt) throws SQLException 

Method Source Code

//package com.java2s;
/*/*from w w w  .j  a  v a 2s  .  c o m*/
 * Microsoft JDBC Driver for SQL Server
 * 
 * Copyright(c) Microsoft Corporation All rights reserved.
 * 
 * This program is made available under the terms of the MIT License. See the LICENSE file in the project root for more information.
 */

import java.sql.SQLException;

public class Main {
    /**
     * mimic "DROP TABLE IF EXISTS ..." for older versions of SQL Server
     */
    public static void dropTableIfExists(String tableName, java.sql.Statement stmt) throws SQLException {
        dropObjectIfExists(tableName, "IsTable", stmt);
    }

    /**
     * actually perform the "DROP TABLE / PROCEDURE"
     */
    private static void dropObjectIfExists(String objectName, String objectProperty, java.sql.Statement stmt)
            throws SQLException {
        StringBuilder sb = new StringBuilder();
        if (!objectName.startsWith("[")) {
            sb.append("[");
        }
        sb.append(objectName);
        if (!objectName.endsWith("]")) {
            sb.append("]");
        }
        String bracketedObjectName = sb.toString();
        String sql = String.format(
                "IF EXISTS " + "( " + "SELECT * from sys.objects "
                        + "WHERE object_id = OBJECT_ID(N'%s') AND OBJECTPROPERTY(object_id, N'%s') = 1 " + ") "
                        + "DROP %s %s ",
                bracketedObjectName, objectProperty, "IsProcedure".equals(objectProperty) ? "PROCEDURE" : "TABLE",
                bracketedObjectName);
        stmt.executeUpdate(sql);
    }
}

Related

  1. dropTable(Connection connection)
  2. dropTable(Connection connection, String tableName)
  3. dropTable(Connection dbConn, String tableName)
  4. dropTable(java.sql.Connection conn, java.lang.String table)
  5. dropTable(Statement st, String query)
  6. dropTablesIfExist(Statement statement)