Kỹ thuật
Sử dụng biến người dùng (@tableName), CONCAT() để xây dựng chuỗi truy vấn động, sau đó PREPARE và EXECUTE.
1. Tạo bảng
mysql> create table DemoTable (
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(20)
);
Query OK, 0 rows affected (0.71 sec)
2. Chèn dữ liệu
mysql> insert into DemoTable(StudentName) values('Chris'),('David'),('Sam'),('Mike');
3. Xem dữ liệu
mysql> select * from DemoTable;
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Chris | | 2 | David | | 3 | Sam | | 4 | Mike | +-----------+-------------+ 4 rows in set (0.00 sec)
4. Sử dụng biến và Prepared 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)
mysql> execute executeQuery;
Kết quả:
+-------------+ | StudentName | +-------------+ | Chris | | David | | Sam | | Mike | +-------------+ 4 rows in set (0.00 sec)
Ứng dụng: Xây dựng truy vấn động trong stored procedure hoặc script quản trị.