MySQL 建立函式時報錯'ERROR 1336 (0A000): Dynamic SQL'

feelpurple發表於2016-09-09
建立函式時報錯
mysql> delimiter $$
mysql> CREATE FUNCTION is_SQLScriptReferenceExist (THE_REFERENCE VARCHAR(75), THE_VERSION_LEVEL_TABLE_NAME VARCHAR(75)) RETURNS INTEGER DETERMINISTIC
    ->     BEGIN
    ->     DECLARE THE_REFERENCE_LABEL VARCHAR(80);
    ->     DECLARE CONTINUE HANDLER FOR NOT FOUND
    ->     BEGIN
    ->     RETURN 0;
    ->     END;
    ->         SELECT concat('select c_reference_label INTO THE_REFERENCE_LABEL from ', THE_VERSION_LEVEL_TABLE_NAME, ' where C_REFERENCE_LABEL = ''', THE_REFERENCE, '''') INTO @stmt;
    ->         PREPARE STMT FROM @stmt;
    ->         EXECUTE STMT;
    ->         /* select c_reference_label into THE_REFERENCE_LABEL from THE_VERSION_LEVEL_TABLE_NAME where C_REFERENCE_LABEL = THE_REFERENCE; */
    ->         RETURN 1;
    ->     END$$
ERROR 1336 (0A000): Dynamic SQL is not allowed in stored function or trigger
mysql> delimiter ;

報錯原因:
MySQL函式和觸發器中不允許使用動態函式

可以改寫成儲存過程
mysql> delimiter $$
mysql> CREATE PROCEDURE is_SQLScriptReferenceExist (IN THE_REFERENCE VARCHAR(75), IN THE_VERSION_LEVEL_TABLE_NAME VARCHAR(75), OUT V_RET INT(2))
    ->     BEGIN
    ->     DECLARE THE_REFERENCE_LABEL VARCHAR(80);
    ->     DECLARE CONTINUE HANDLER FOR NOT FOUND
    ->     BEGIN
    ->     SET V_RET = 0;
    ->     END;
    ->         SELECT concat('select c_reference_label INTO THE_REFERENCE_LABEL from ', THE_VERSION_LEVEL_TABLE_NAME, ' where C_REFERENCE_LABEL = ''', THE_REFERENCE, '''') INTO @stmt;
    ->         PREPARE STMT FROM @stmt;
    ->         EXECUTE STMT;
    ->         /* select c_reference_label into THE_REFERENCE_LABEL from THE_VERSION_LEVEL_TABLE_NAME where C_REFERENCE_LABEL = THE_REFERENCE; */
    ->         SET V_RET = 1;
    ->     END$$
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26506993/viewspace-2124763/,如需轉載,請註明出處,否則將追究法律責任。

相關文章