In mySQL 5, is there a way to drop all foreign key constraints on a table with one SQL statement without referring to them by name?
I'm writing a DB update script, and unfortunately some of the sites had constraints created with "wrong" names. I'm trying to avoid going in and getting the actual constraint names from the DB and inserting them back into SQL statements.
You can drop a foreign key constraint using the following ALTER TABLE syntax: ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol; If the FOREIGN KEY clause defined a CONSTRAINT name when you created the constraint, you can refer to that name to drop the foreign key constraint.
To drop a foreign key from a table, use the ALTER TABLE clause with the name of the table (in our example, student ) followed by the clause DROP CONSTRAINT with the name of the foreign key constraint.
Dropping Tables/Schemas/Databases For example, when dropping a database, if the database contains a primary/unique key which is referenced by a foreign key from another database, the referencing foreign keys are also dropped.
To delete a foreign key constraint In Object Explorer, expand the table with the constraint and then expand Keys. Right-click the constraint and then click Delete. In the Delete Object dialog box, click OK.
I have a solution similar to Bing's answer, but it takes it one step further to be automatic and reusable in a procedure.
DROP PROCEDURE IF EXISTS dropForeignKeysFromTable;
delimiter ///
create procedure dropForeignKeysFromTable(IN param_table_schema varchar(255), IN param_table_name varchar(255))
begin
declare done int default FALSE;
declare dropCommand varchar(255);
declare dropCur cursor for
select concat('alter table ',table_schema,'.',table_name,' DROP FOREIGN KEY ',constraint_name, ';')
from information_schema.table_constraints
where constraint_type='FOREIGN KEY'
and table_name = param_table_name
and table_schema = param_table_schema;
declare continue handler for not found set done = true;
open dropCur;
read_loop: loop
fetch dropCur into dropCommand;
if done then
leave read_loop;
end if;
set @sdropCommand = dropCommand;
prepare dropClientUpdateKeyStmt from @sdropCommand;
execute dropClientUpdateKeyStmt;
deallocate prepare dropClientUpdateKeyStmt;
end loop;
close dropCur;
end///
delimiter ;
Since a prepared statement can only handle one statement at a time, the procedure loops through the foreign keys using a cursor and executes each drop one at a time.
To use the procedure on one of your tables just use the following, replacing table_schema and table_name with your values:
call dropForeignKeysFromTable('table_schema', 'table_name');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With