MySQL Dynamic SQL statement runs with TIME table name

Source: Internet
Author: User

1. Descriptive narrative

When it comes to using data, we need a lot of databases and we want to use time to make table names to differentiate. However, MySQL does not support the use of variable names for table names or column names in stored procedures.


For example, there is a table we want to name "2015-07-16 12:00:00".

2. How to Solve

It is easy to assume that it is simply a replacement of a regular table name. You can use the following SQL statements directly:
  alter table old_table_name rename new_table_name
But to use time as the table name, dynamic naming can not be enough. First we can get the current time of the system with the now () function. To find a way to support dynamic database operations in the form of variables, in the version number above MySQL5.1. The Prepare statement can support this operation.


We can use set @var=... the set variable, and then use prepare stml from @var the SET dynamic SQL statement, and finally EXECUTE stml; run the statement.
The following is the name of the time table. Dynamically altering the SQL run of a table:
  

@asql=concat(‘alter table old_table_name rename `‘,NOW(),‘`‘);@asql;EXECUTE stml;

Here we use the concat function in MySQL, the function of which is string concatenation. I believe that the students who know how to program are not unfamiliar with it.
Usage:
Concat (STR1,STR2,...)

Returns the string resulting from the result of the join. Note If any of the parameters is null, the return value is NUL.
Attached with a knot running Fruit chart:
  

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqv/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/gravity /southeast "alt=" Re "title=" ">

MySQL Dynamic SQL statement runs with TIME table name

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.