How can we use prepared statements in a stored procedure?


If we want to use prepared statements in a stored procedure then it must be written inside the BEGIN and END block. To understand it, we are creating an example with the help of which we can get all the records from a table by passing the name of the table as a parameter of the stored procedure.

Example

mysql> DELIMITER //
mysql> Create procedure tbl_detail(tab_name Varchar(40))
    -> BEGIN
    -> SET @A:= CONCAT('Select * from',' ',tab_name);
    -> Prepare stmt FROM @A;
    -> EXECUTE stmt;
    -> END //
Query OK, 0 rows affected (0.00 sec)

Now invoke this procedure by giving the name of the table as its parameter and it will show all the records of that table.

mysql> DELIMITER;
mysql> CALL tbl_detail('Student’);
+------+--------+
| Id   | Name   |
+------+--------+
|    1 | Ram    |
|    2 | Shyam  |
|    3 | Gaurav |
+------+--------+
3 rows in set (0.00 sec)
Query OK, 0 rows affected (0.03 sec)

Updated on: 22-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements