MySQL dynamically creates a table and stores data into Table shards.

Source: Internet
Author: User
MySQL dynamically creates a table and stores data in table shards. For more information, see.

MySQL dynamically creates a table and stores data in table shards. For more information, see.

The Code is as follows:
BEGIN
DECLARE '@ I' int (11 );
DECLARE '@ siteCount' int (11 );
DECLARE '@ sqlstr' VARCHAR (2560 );
DECLARE '@ sqlinsert' VARCHAR (2560); // DECLARE the variable above
Select count (0) into '@ siteCount' FROM tbl_base_site; // calculates the total number of records in the tbl_base_site table.
Set '@ I' = 1;
WHILE ('@ I'-1) * 300 <'@ siteCount' DO // while LOOP execution
SET @ sqlstr = CONCAT ('create TABLE tbl_base_syslog ',' @ I ',' (syslog_id INT (11) AUTO_INCREMENT PRIMARY KEY,
Create_user VARCHAR (32 ),
Description text,
Create_time datetime,
Site_id INT (11 ),
Ip VARCHAR (64 ),
Version_id SMALLINT (2 ),
Module_identity VARCHAR (64 ),
Right_name VARCHAR (64)
)');
Prepare stmt from @ sqlstr;
Execute stmt;
// The above implementation dynamically creates a table
SET @ sqlinsert = CONCAT ('insert INTO tbl_base_syslog ',' @ I ','(
Syslog_id,
Create_user,
Description,
Create_time,
Site_id,
Ip,
Version_id,
Module_identity,
Right_name)
SELECT syslog_id,
Create_user,
Description,
Create_time,
Site_id,
Ip,
Version_id,
Module_identity,
Right_name
FROM tbl_base_syslog
WHERE site_id IN (select tbs. site_id from (select site_id from tbl_base_site limit ',' @ I '* 300,', 300) as tbs)
Order by syslog_id ');
Prepare stmt from @ sqlinsert;
Execute stmt;
// The above implementation inserts a query record from a table into a dynamically created new table
SET '@ I' = '@ I' + 1;

End while;
END

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.