在 MySQL 中根据当前年份创建一个动态表名,如 2019

mysqlmysqli database

要创建类似年份 (2019) 的表名,请使用 PREPARE 语句。让我们首先创建一个表 −

mysql> create table DemoTable1959
   (
   UserName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable1959 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1959 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1959 values('Bob');
Query OK, 1 row affected (0.00 sec)

使用 select 语句显示表中的所有记录 −

mysql> select * from DemoTable1959;

这将产生以下输出 −

+----------+
| UserName |
+----------+
| Chris    |
| David    |
| Bob      |
+----------+
3 rows in set (0.00 sec)

这是根据当前年份创建动态表名的查询

mysql> set @dynamicQuery = CONCAT('create table `', date_format(curdate(),'%Y'), '` as select UserName from DemoTable1959');
Query OK, 0 rows affected (0.00 sec)
mysql> prepare st from @dynamicQuery;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute st;
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

使用 select 语句显示表中的所有记录。当前年份是 2019 −

mysql> select * from `2019`;

这将产生以下输出 −

+----------+
| UserName |
+----------+
| Chris    |
| David    |
| Bob      |
+----------+
3 rows in set (0.00 sec)

相关文章