Implement Dynamic SQL query inside a MySQL stored procedure?

MySQLMySQLi Database

For dynamic SQL query in a stored procedure, use the concept of PREPARE STATEMENT. Let us first create a table −

mysql> create table DemoTable2033
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2033(Name) values('Chris');
Query OK, 1 row affected (0.85 sec)

mysql> insert into DemoTable2033(Name) values('Bob');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable2033(Name) values('David');
Query OK, 1 row affected (0.24 sec)

mysql> insert into DemoTable2033(Name) values('Mike');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable2033;

This will produce the following output −

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Chris |
| 2  | Bob   |
| 3  | David |
| 4  | Mike  |
+----+-------+
4 rows in set (0.00 sec)

Following is the query to create a stored procedure and implement dynamic 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
   -> //
Query OK, 0 rows affected (0.13 sec)

mysql> delimiter ;

Call the stored procedure −

mysql> call dynamic_query();

This will produce the following output −

+----+-------+
| Id | Name  |
+----+-------+
| 3  | David |
+----+-------+
1 row in set (0.04 sec)
Query OK, 0 rows affected (0.05 sec)
raja
Published on 07-Apr-2020 11:29:48
Advertisements