Set user-defined variable with table name in MySQL prepare statement?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20)
);
Query OK, 0 rows affected (0.71 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable(StudentName) values('David');
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable(StudentName) values('Sam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('Mike');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       1 | Chris       |
|       2 | David       |
|       3 | Sam       |
|       4 | Mike       |
+-----------+-------------+
4 rows in set (0.00 sec)

Here is the how you can use a user-defined variable to set a table name and work with MySQL prepare statement −

mysql> set @tableName = 'DemoTable';
Query OK, 0 rows affected (0.04 sec)
mysql> set @queryToSelectStudentName := concat('select StudentName from ',@tableName);
Query OK, 0 rows affected (0.28 sec)
mysql> prepare executeQuery from @queryToSelectStudentName;
Query OK, 0 rows affected (0.04 sec)
Statement prepared
mysql> execute executeQuery;

This will produce the following output −

+-------------+
| StudentName |
+-------------+
| Chris       |
| David       |
| Sam       |
| Mike       |
+-------------+
4 rows in set (0.00 sec)
raja
Published on 10-Oct-2019 12:06:31
Advertisements