MySQL dynamic table creation, data table sharding stored procedure _ MySQL
Source: Internet
Author: User
MySQL dynamically creates a table and stores data in sub-tables in bitsCN.com.
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;
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.