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.
Is there a way to fully automating retrieving the foreign key name for use in the DROP FOREIGN KEY
clause?
2
Answers
You have to put the entire
DROP
statement into a string that you execute withPREPARE
andEXECUTE
.You can’t directly use a variable in the
DROP FOREIGN KEY
, but you can construct a dynamic sql statement and execute it.