开发者

Drop Mysql table column with Foreign key constraint

开发者 https://www.devze.com 2023-03-10 22:07 出处:网络
How to drop column with all related foreign key and other constraint i开发者_开发百科n mysql ?Use SET FOREIGN_KEY_CHECKS = 0; and then alter the table that contains the constraint definition. After yo

How to drop column with all related foreign key and other constraint i开发者_开发百科n mysql ?


Use SET FOREIGN_KEY_CHECKS = 0; and then alter the table that contains the constraint definition. After you're done, turn FOREIGN_KEY_CHECKS back to 1.


AFAIK on MySQL you have to manually delete the constraints before dropping the column.

The ON DELETE CASCADE clause would affect the table only if you created the constraint with that clause and it is only needed to delete the foreign rows connected with that table with that constraint.


Use ON DELETE CASCADE

http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html


if you're using java:

public void deleteColumn(Connection connection, String tableName, String columnName) throws SQLException {
    // Drop all constraints that contain the specified column
    {
        final ResultSet resultSet = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY).executeQuery("select CONSTRAINT_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_SCHEMA = SCHEMA() and TABLE_NAME = '" + tableName + "' and COLUMN_NAME = '" + columnName + "'");
        while (resultSet.next()) {
            final String constraintName = resultSet.getString("CONSTRAINT_NAME");
            connection.createStatement().executeUpdate("ALTER TABLE `" + tableName + "` DROP FOREIGN KEY`" + constraintName + "`"); // Drop the foreign key constraint          
        }
        resultSet.close();
    }

    // Drop all indexes that contain the specified column:
    {
        final ResultSet resultSet = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY).executeQuery("SHOW INDEX FROM `" + tableName + "` where column_name = '" + columnName+ "'");
        while (resultSet.next()) {
            final String keyName = resultSet.getString("Key_name");
            connection.createStatement().executeUpdate("ALTER TABLE `" + tableName + "` DROP INDEX `" + keyName + "`"); // Drop the index               
        }
        resultSet.close();
    }

    // Drop the column:
    connection.createStatement().executeUpdate("ALTER TABLE `" + tableName + "` DROP COLUMN `" + columnName + "`"); // Drop the column
}
0

精彩评论

暂无评论...
验证码 换一张
取 消