如何在执行特定查询集之前检查mysql中的空条件?

时间:2014-06-23 10:17:24

标签: mysql if-statement conditional-statements ifnull

我正在尝试在不同的5个数据库中执行以下脚本。

SET @CONSTRAINT_NAME = (SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'StudentMaster'
AND TABLE_NAME = 'StudentSubjectMa'
AND CONSTRAINT_SCHEMA = DATABASE());

现在,我想在此处查看如果@CONSTRAINT_NAMENOT NULL,则只应执行以下语句。有可能吗?

    SET @DROP_CONSTRAINT_SQL = CONCAT("ALTER TABLE StudentSubjectMarksMap 
    DROP FOREIGN KEY `", @CONSTRAINT_NAME , "`");

    PREPARE DROP_CONSTRAINT_SQL_STMT FROM @DROP_CONSTRAINT_SQL;
    EXECUTE DROP_CONSTRAINT_SQL_STMT;
    DROP PREPARE DROP_CONSTRAINT_SQL_STMT;

1 个答案:

答案 0 :(得分:1)

是的,可以使用标准IF声明:

IF @CONSTRAINT_NAME IS NOT NULL THEN 
    SET @DROP_CONSTRAINT_SQL = CONCAT("ALTER TABLE StudentSubjectMarksMap 
    DROP FOREIGN KEY `", @CONSTRAINT_NAME , "`");

    PREPARE DROP_CONSTRAINT_SQL_STMT FROM @DROP_CONSTRAINT_SQL;
    EXECUTE DROP_CONSTRAINT_SQL_STMT;
    DROP PREPARE DROP_CONSTRAINT_SQL_STMT;
END IF

有关详细信息,请参阅reference manual