
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set user-defined variable with table name in MySQL prepare statement?
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)
- Related Questions & Answers
- Select into a user-defined variable with MySQL
- MySQL ORDER BY with numeric user-defined variable?
- Perform MySQL SELECT INTO user-defined variable
- MongoDB query to set user defined variable into query?
- Using variables with MySQL prepare statement
- Set custom messages by working with MySQL IF Statements and SELECT in a user-defined variable
- Updating a MySQL table row column by appending a value from user defined variable?
- In MySQL, why a client cannot use a user-defined variable defined by another client?
- How to set different auto-increment ids for two tables with a user-defined variable?
- MySQL CREATE USER with a variable?
- Show a MySQL user-defined variables values in the result table?
- Using User-Defined Variables in MySQL
- Set user variable from result of query in MySQL?
- C++ set for user defined data type?
- How Can we permanently define user-defined variable for a client in MySQL?
Advertisements