MySQL dynamic SQL statement execution uses time as the table name, mysqlsql
1. Description
When using data, we need a lot of databases and want to use time as the table name to differentiate them. However, MySQL does not support using variable names as table names or column names during storage.
For example, we want to name a table named "12:00:00.
2. Solution
To replace a common table name, you can simply use the following SQL statement:
Alter table old_table_name rename new_table_name
However, the table name must be time-based, and dynamic names cannot be used. First, we can use the NOW () function to obtain the current system time. To support dynamic database operations in the form of variables, the prepare statement can support such operations in MySQL or later versions.
We can useSet @ var =...
Set the variable, and then usePrepare stml from @ var
Set dynamic SQL statements and useEXECUTE stml;
Execute the statement.
The SQL Execution Process of a table is dynamically modified using the time as the table name:
Set @ asql = concat ('alter table old_table_name rename' ', NOW (), '''); prepare stml from @ asql; EXECUTE stml;
Here we use the concat function in MySQL, which is used for String concatenation. I believe that programmers are familiar with this.
Usage:
Concat (str1, str2 ,...)
Returns the string generated by the connection parameter. Note that if any parameter is NULL, the return value is NUL.
The following figure shows the running result:
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.