primary ALTER TABLE腳本中的MySQL變量



mysql create table alter (1)

你好以下過程將不得不將所有的約束從一個表移動到另一個表,但是我在約束被刪除的地方遇到了一些困難。

問題:如何在下面的行中使用變量

ALTER TABLE var_referenced_table_name DROP FOREIGN KEY var_constraint_name;

當我使用時,我收到以下錯誤

Error Code: 1146. Table 'oaf_businesslink_dev.var_referenced_table_name' doesn't exist

MySQL不會將var_referenced_table_namevar_constraint_name識別為變量。

DELIMITER //
DROP PROCEDURE IF EXISTS AlterConstraints//
CREATE PROCEDURE AlterConstraints()
BEGIN

    DECLARE schema_name VARCHAR(60) DEFAULT 'oaf_businesslink_dev';
    DECLARE table_name VARCHAR(60) DEFAULT 'wp_systemuser';

    DECLARE finished INTEGER DEFAULT 0;
    DECLARE total INTEGER DEFAULT 0;    

    DECLARE var_constraint_name VARCHAR(60) DEFAULT '';
    DECLARE var_table_name VARCHAR(60) DEFAULT '';
    DECLARE var_column_name VARCHAR(60) DEFAULT '';
    DECLARE var_referenced_table_name VARCHAR(60) DEFAULT '';
    DECLARE var_referenced_column_name VARCHAR(60) DEFAULT '';

    DECLARE cur_constraints CURSOR FOR SELECT constraint_Name, table_name,column_name,referenced_table_name,referenced_column_name
    FROM information_schema.key_column_usage
    WHERE constraint_schema = schema_name
        AND referenced_table_name = table_name
        AND table_name IS NOT NULL;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
    OPEN cur_constraints;

    get_constraint: 
    LOOP FETCH cur_constraints 
    INTO var_constraint_name
        ,var_table_name
        ,var_column_name
        ,var_referenced_table_name
        ,var_referenced_column_name;          

        IF finished THEN
            LEAVE get_constraint;
        END IF; 

        /* Get Constraint Count */
        SET total = total + 1;

        /* Remove Constraint */
        IF EXISTS(SELECT * FROM information_schema.TABLE_CONSTRAINTS
            WHERE CONSTRAINT_NAME = var_constraint_name AND TABLE_NAME = var_referenced_table_name AND TABLE_SCHEMA = schema_name)
            THEN
            /* 
             * Error Code: 1146. Table 'oaf_businesslink_dev.var_referenced_table_name' doesn't exist
             */
            ALTER TABLE var_referenced_table_name DROP FOREIGN KEY var_constraint_name;
        END IF;

        /* Change Datatype to BIGINT */

        /* Recreate Constraint to new table */
    END

    LOOP get_constraint;
    CLOSE cur_constraints;
    SELECT total;

END
//
DELIMITER ;

CALL AlterConstraints();

提前致謝。


通過將變量用作列名和表,最好將查詢聲明為“字符串”,然後通過Prepared Statement執行該字符串。

這可以通過兩種方式來完成,可以通過CONCAT()來構建完整的字符串,也可以通過使用帶有參數的PREPARE來完成:

SET @query = CONCAT('ALTER TABLE ', var_referenced_table_name, ' DROP FOREIGN KEY ', var_constraint_name, ';');
PREPARE stmt FROM @query; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;




alter-table