'MySQL ALTER TABLE with arguments in stored procedure
In a MySQL migration script, I'm trying to drop all the foreign keys of a table without knowing the name of the constraints themselves. I need this because I can only be aware of the constraints names in a particular database installation, but the script has to work also in other installations where the name is unknown at current script coding time.
Here is my first guess of a stored procedure, but it doesn't work. In particular it complains about the '?' in ALTER TABLE.
DELIMITER $$
DROP PROCEDURE IF EXISTS drop_foreign_key_documents $$
CREATE PROCEDURE drop_foreign_key_documents ( )
BEGIN
WHILE (SELECT COUNT(*) AS index_exists FROM `information_schema`.`TABLE_CONSTRAINTS` c WHERE `c`.`CONSTRAINT_TYPE` LIKE '%FOREIGN%' AND `c`.`TABLE_NAME`='documents' and `c`.`TABLE_SCHEMA`='mydb') > 0 DO
SET @ctype = '%FOREIGN%';
SET @tname = 'documents';
SET @dbname = 'mydb';
SET @n = 'select `CONSTRAINT_NAME` INTO @cname FROM `information_schema`.`TABLE_CONSTRAINTS` c WHERE `c`.`CONSTRAINT_TYPE` LIKE ? AND `c`.`TABLE_NAME`=? and `c`.`TABLE_SCHEMA`=? LIMIT 0,1';
PREPARE stmt FROM @n;
EXECUTE stmt USING @ctype,@tname,@dbname;
SELECT @cname;
SET @s = 'ALTER TABLE `documents` DROP FOREIGN KEY ?';
PREPARE stmtd FROM @s;
EXECUTE stmtd USING @cname;
END WHILE;
END $$
DELIMITER ;
CALL drop_foreign_key_documents;
The output of MySQL is:
@cname
documents_ibfk_13
ERROR 1064 (42000) at line 23: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
Now I can imagine why it complains: the ALTER TABLE statement cannot use '?' because the constraint name is not part of a WHERE clause and so it cannot be replaced by a positional parameter. What I don't know is how to build a parametrized ALTER TABLE statement.
Solution 1:[1]
Obvious answer:
SET @s = CONCAT('ALTER TABLE `documents` DROP FOREIGN KEY ', @cname);
PREPARE stmtd FROM @s;
EXECUTE stmtd;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | vinzee |