让我们首先创建一个表-
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(StudentName) values('Chris'); mysql> insert into DemoTable(StudentName) values('David'); mysql> insert into DemoTable(StudentName) values('Sam'); mysql> insert into DemoTable(StudentName) values('Mike');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Chris | | 2 | David | | 3 | Sam | | 4 | Mike | +-----------+-------------+ 4 rows in set (0.00 sec)
这是如何使用用户定义的变量来设置表名并使用MySQL prepare语句的方法-
mysql> set @tableName −= 'DemoTable'; mysql> set @queryToSelectStudentName := concat('select StudentName from ',@tableName); mysql> prepare executeQuery from @queryToSelectStudentName; Statement prepared mysql> execute executeQuery;
这将产生以下输出-
+-------------+ | StudentName | +-------------+ | Chris | | David | | Sam | | Mike | +-------------+ 4 rows in set (0.00 sec)