Dynamic SQL to get a parameter and use it in LIKE for a new table created inside a stored procedure

MySQLMySQLi Database

For this, use prepared statement. Let us first create a table −

mysql> create table DemoTable1973
   (
   StudentId int,
   StudentName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

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)

Display all records from the table using select statement −

mysql> select * from DemoTable1973;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       101 | Chris       |
|       102 | John Doe    |
|       103 | David       |
|       104 | John Smith  |
+-----------+-------------+
4 rows in set (0.00 sec)

Following is the query to create a stored procedure and a new table with LIKE clause having a value from procedure call −

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 the stored procedure using call command −

mysql> call demo_create('newTableName','John');
Query OK, 2 rows affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from newTableName;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       102 | John Doe    |
|       104 | John Smith  |
+-----------+-------------+
2 rows in set (0.00 sec)
raja
Published on 31-Dec-2019 12:24:33
Advertisements