在MySQL迁移脚本中,我试图删除表的所有外键,而不知道约束本身的名称。我需要这个,因为我只能知道特定数据库安装中的约束名称,但是脚本也必须在当前脚本编码时名称未知的其他安装中工作。
这是我对存储过程的第一次猜测,但它不起作用。特别是它抱怨'?'在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;
MySQL的输出是:
@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
现在我可以想象它为什么抱怨:ALTER TABLE语句不能使用'?'因为约束名称不是WHERE子句的一部分,所以它不能被位置参数替换。我不知道的是如何构建参数化的ALTER TABLE语句。
答案 0 :(得分:4)
明显的答案:
SET @s = CONCAT('ALTER TABLE `documents` DROP FOREIGN KEY ', @cname);
PREPARE stmtd FROM @s;
EXECUTE stmtd;
抱歉这个愚蠢的问题......