动态 SQL 获得参数并在存储过程中创建的表的 LIKE 子句中使用该参数
为此,请使用准备好的语句。我们首先创建一个表 -
mysql> create table DemoTable1973 ( StudentId int, StudentName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1973 values(101,'Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1973 values(102,'John Doe'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1973 values(103,'David'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1973 values(104,'John Smith'); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1973;
这将产生以下输出 -
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 101 | Chris | | 102 | John Doe | | 103 | David | | 104 | John Smith | +-----------+-------------+ 4 rows in set (0.00 sec)
以下是创建存储过程和新表(具有来自过程调用的值的 LIKE 子句)的查询 -
mysql> DELIMITER //
mysql> create PROCEDURE demo_create(IN newTableName varchar(20),IN tbl varchar(20))
BEGIN
DROP TABLE IF EXISTS newTableName;
SET @query= CONCAT('CREATE TABLE newTableName as SELECT * from DemoTable1973 WHERE StudentName like ''%',tbl,'%''');
PREPARE ps FROM @query;
EXECUTE ps;
END
//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;使用 call 命令调用存储过程 -
mysql> call demo_create('newTableName','John');
Query OK, 2 rows affected (0.00 sec)使用 select 语句显示表中的所有记录 -
mysql> select * from newTableName;
这将产生以下输出 -
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 102 | John Doe | | 104 | John Smith | +-----------+-------------+ 2 rows in set (0.00 sec)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP