简体   繁体   English

MySQL ALTER TABLE与存储过程中的参数

[英]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. 在MySQL迁移脚本中,我试图删除表的所有外键,而不知道约束本身的名称。 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. 在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: 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

Now I can imagine why it complains: the ALTER TABLE statement cannot use '?' 现在我可以想象为什么它抱怨:ALTER TABLE语句不能使用'?' because the constraint name is not part of a WHERE clause and so it cannot be replaced by a positional parameter. 因为约束名称不是WHERE子句的一部分,所以它不能被位置参数替换。 What I don't know is how to build a parametrized ALTER TABLE statement. 我不知道的是如何构建参数化的ALTER TABLE语句。

Obvious answer: 明显的答案:

SET @s = CONCAT('ALTER TABLE `documents` DROP FOREIGN KEY ', @cname);
PREPARE stmtd FROM @s;
EXECUTE stmtd;

Sorry for the stupid question... 对不起这个愚蠢的问题......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM