动态 SQL 获取参数并在 LIKE 中使用它来创建存储过程内的新表

mysqlmysqli database更新于 2024/12/8 2:20:17

为此,请使用准备好的语句。让我们首先创建一个表 −

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)

相关文章


有用资源