Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to drop foreign key using a subselect?

First off, we’re using MySQL 5.

I’d like to do something like the following:

SET @fkcn = (SELECT CONSTRAINT_NAME
             FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
             WHERE REFERENCED_TABLE_SCHEMA = (SELECT DATABASE())
               AND REFERENCED_TABLE_NAME = "ProviderOrder");
ALTER TABLE AuditProviderOrder
    DROP FOREIGN KEY @fkcn,
    DROP COLUMN ProviderOrderID;

But MySQL 5 complains that it’s invalid syntax. I’ve tried DROP FOREIGN KEY (SELECT @fkcn) as well as inlining @fkcn with similar syntax issues.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to fully automating retrieving the foreign key name for use in the DROP FOREIGN KEY clause?

>Solution :

You have to put the entire DROP statement into a string that you execute with PREPARE and EXECUTE.

SET @drop = CONCAT('ALTER TABLE AuditProviderOrder
    DROP FOREIGN KEY ', @fkcn, ',
    DROP COLUMN ProviderOrderID');
PREPARE stmt FROM @drop;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading