Using variables with MySQL prepare statement


Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(20),
   LastName varchar(20)
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName,LastName) values('John','Smith');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(FirstName,LastName) values('David','Miller');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(FirstName,LastName) values('John','Doe');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(FirstName,LastName) values('Chris','Brown');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+----------+
| Id | FirstName | LastName |
+----+-----------+----------+
|  1 | John      | Smith    |
|  2 | David     | Miller   |
|  3 | John      | Doe      |
|  4 | Chris     | Brown    |
+----+-----------+----------+
4 rows in set (0.00 sec)

Following is the query to set variables while using prepare statement in MySQL −

mysql> set @yourTableName :='DemoTable';
Query OK, 0 rows affected (0.00 sec)
mysql> set @query :=CONCAT('select `LastName` from ',@yourTableName, ' where Id=3 ');
Query OK, 0 rows affected (0.00 sec)
mysql> prepare myStatement from @query;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute myStatement;

This will produce the following output −

+----------+
| LastName |
+----------+
| Doe      |
+----------+
1 row in set (0.00 sec)

Updated on: 10-Oct-2019

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements