gpt4 book ai didi

mysql - mysql存储过程中的动态sql

转载 作者:行者123 更新时间:2023-11-29 07:44:41 28 4
gpt4 key购买 nike

我正在尝试编写一个通用的 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 之间的区别很重要和常规参数13.1.15. CREATE PROCEDURE and CREATE FUNCTION Syntax ,是不同的变量。

在您的示例中,@sql_queryNULL,并且 sql_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

关于mysql - mysql存储过程中的动态sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28150632/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com