对于存储过程中的动态SQL查询,请使用PREPARE STATEMENT的概念。让我们首先创建一个表-
mysql> create table DemoTable2033 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable2033(Name) values('Chris'); mysql> insert into DemoTable2033(Name) values('Bob'); mysql> insert into DemoTable2033(Name) values('David'); mysql> insert into DemoTable2033(Name) values('Mike');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable2033;
这将产生以下输出-
+----+-------+ | Id | Name | +----+-------+ | 1 | Chris | | 2 | Bob | | 3 | David | | 4 | Mike | +----+-------+ 4 rows in set (0.00 sec)
以下是创建存储过程并实现动态SQL的查询-
mysql> delimiter // mysql> create procedure dynamic_query() -> begin -> set @query=concat("select *from DemoTable2033 where Id=3"); -> prepare st from @query; -> execute st; -> end -> // mysql> delimiter ;
调用存储过程-
mysql> call dynamic_query();
这将产生以下输出-
+----+-------+ | Id | Name | +----+-------+ | 3 | David | +----+-------+ 1 row in set (0.04 sec)