To create a table name like year (2019), use PREPARE statement. Let us first create a table −
mysql> create table DemoTable1959 ( UserName varchar(20) ); Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
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)
Display all records from the table using select statement −
mysql> select * from DemoTable1959;
This will produce the following output −
+----------+ | UserName | +----------+ | Chris | | David | | Bob | +----------+ 3 rows in set (0.00 sec)
Here is the query to create a dynamic table name from current year
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
Display all records from the table using select statement. Here the current year is 2019 −
mysql> select * from `2019`;
This will produce the following output −
+----------+ | UserName | +----------+ | Chris | | David | | Bob | +----------+ 3 rows in set (0.00 sec)