mysql 存储过程中的动态 sql

dynamic sql in mysql stored proceure

我正在尝试编写一个通用的 sql 过程,它可以将任何字符串作为 sql 语句执行。

这是过程定义。

DELIMITER //

DROP PROCEDURE IF EXISTS execute_dynamic_sql;
CREATE PROCEDURE execute_dynamic_sql (IN sql_query longtext)
BEGIN
SELECT sql_query;
PREPARE stmt FROM @sql_query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //

我是这样调用上面的函数的

mysql> call execute_dynamic_sql('show tables');
    -> //
+-------------+
| sql_query   |
+-------------+
| show tables |
+-------------+
1 row in set (0.00 sec)

ERROR 1064 (42000): 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 'NULL' at line 1
mysql> #

谁能告诉我为什么会出现错误?

重要的是要指出 9.4. User-Defined Variables and routine parameters 13.1.15. CREATE PROCEDURE and CREATE FUNCTION Syntax 之间的区别,是不同的变量。

在您的示例中,@sql_queryNULLsql_query 分配给 SHOW TABLES

尝试:

DELIMITER//

CREATE PROCEDURE `execute_dynamic_sql` (IN `sql_query` LONGTEXT)
BEGIN
  SET @`sql_query` := `sql_query`;
  PREPARE `stmt` FROM @`sql_query`;
  EXECUTE `stmt`;
  DEALLOCATE PREPARE `stmt`;
END//

DELIMITER;

SQL Fiddle demo