How to create a table by month in MySQL stored procedure

How to create a table by month in MySQL stored procedure

Without going into details, let's go straight to the code. Welcome to communicate and learn together.

Create a stored procedure to create a table by month. The SQL statement is as follows:

DELIMITER // 
DROP PROCEDURE IF EXISTS create_table_by_month //
CREATE PROCEDURE `create_table_by_month`()
BEGIN

  #--Declare the variable in advance, which will be used later DECLARE nextMonth varchar(20);
    DECLARE nextTABLE varchar(20);
    DECLARE csql varchar(5210);
    DECLARE outputParam int;
    DECLARE tableName_1 varchar(20);
    DECLARE tableName_2 varchar(20);
    DECLARE table_prefix varchar(20);

  #--Get the next month SELECT SUBSTR(replace(DATE_ADD(CURDATE(), INTERVAL 1 MONTH), '-', ''), 1, 6) INTO @nextMonth;
  #--Split and analyze the above SQL statements:
  #MySQL time function date_add() adds a time interval to the date. This sql means the date one month after the current date #select DATE_ADD(CURDATE(), INTERVAL 1 MONTH); 
  ##Return 20201006
  #select replace('2020-10-06', '-', '');
  ##Return 20201006
  #select replace(DATE_ADD(CURDATE(), INTERVAL 1 MONTH), '-', '');
  ## Return to 202010
  #SELECT SUBSTR(20201006,1,6);
  ##Assign value to variable @nextMonth #SELECT SUBSTR(20201006,1,6) INTO @nextMonth;

# Table 1
    #Set the table prefix variable value to td_user_banks_log_
    set @table_prefix = 'td_user_banks_log_';

    #Define the name of table 1 SET @tableName_1 = CONCAT(@table_prefix, @nextMonth);
    ##Define the SQL statement to create a table set @csql=concat("create table if not exists ",@tableName_1,"(
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `app_id` varchar(100) NOT NULL,
        `user_id` int(11) NOT NULL DEFAULT '0' COMMENT 'User ID',
        `type` tinyint(2) NOT NULL DEFAULT '1' COMMENT '1 Sign-in Reward 2 Activity Reward 3 Redemption',
        `gold_coin` int(11) NOT NULL,
        `remarks` varchar(200) NOT NULL DEFAULT '' COMMENT 'Remarks',
        `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        KEY `app_id` (`app_id`),
        KEY `user_id` (`user_id`),
        KEY `type` (`type`),
        KEY `create_at` (`create_at`)
      )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
  #PREPARE Introduction:
  ##The statement is used to prepare a statement and specify the name statement_name for later reference. Statement names are not case sensitive.
  ##preparable_stmt can be a literal string or a user variable containing the statement text. The text must represent a single SQL statement, not multiple statements.
  PREPARE create_stmt from @csql; 
    EXECUTE create_stmt;
  DEALLOCATE PREPARE create_stmt;

# Table 2 and Table 1 have the same SQL, so we will not introduce them here:
    set @table_prefix = 'td_sign_log_';

    SET @tableName_2 = CONCAT(@table_prefix, @nextMonth);

    set @csql=concat("create table if not exists ",@tableName_2,"(
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `app_id` varchar(100) NOT NULL,
      `user_id` int(11) NOT NULL,
      `day` int(11) NOT NULL DEFAULT '0' COMMENT 'day',
      `sign_type` tinyint(2) NOT NULL DEFAULT '1' COMMENT '1 Sign-in 2 Make-up sign-in 3 Accumulated reward',
      `type` tinyint(2) NOT NULL DEFAULT '1' COMMENT '1 gold coin',
      `num` int(11) NOT NULL DEFAULT '0',
      `data_id` int(11) NOT NULL DEFAULT '0',
      `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      KEY `app_id` (`app_id`),
      KEY `user_id` (`user_id`),
      KEY `type` (`type`),
      KEY `data_id` (`data_id`),
      KEY `create_at` (`create_at`),
      KEY `sign_type` (`sign_type`),
      KEY `day` (`day`)
    )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    PREPARE create_stmt from @csql; 
    EXECUTE create_stmt;
    DEALLOCATE PREPARE create_stmt;

    SELECT COUNT(1) INTO @outputParam FROM information_schema.`TABLES` WHERE TABLE_NAME in (@tableName_1, @tableName_2);
    SELECT @outputParam;

END //
delimiter ;
#--Create a scheduled task for the current month's table every month:

create EVENT `create_table_by_month` ON SCHEDULE EVERY 1 MONTH STARTS '2020-09-06 12:40:00' ON COMPLETION NOT PRESERVE ENABLE DO call create_table_by_month();

Common sense tip: In the scheduled task, call the stored procedure SQL1 statement to execute at a specific time. The specified time must be in the future.

#View the SQL statement for creating a stored procedure:

show create PROCEDURE create_table_by_month_G
#Delete the stored procedure:

DROP PROCEDURE IF EXISTS create_table_by_month;
#Delete the scheduled task drop event create_table_by_month1;

The above stored procedure SQL statements and timer SQL statements are used in the production environment

#Troubleshooting errors:

I found that the MySQL log reported an error. The index key field added in the SQL statement of the original stored procedure happened to be a field that did not exist in the table, so the following error was reported. So remove the index key field in the stored procedure and the SQL will be OK.

2020-09-06T12:40:00.244879+08:00 604392 [ERROR] Event Scheduler: [root@localhost][test0001.create_table_by_month1] Key column 'sign_date' doesn't exist in table
2020-09-06T12:40:00.244926+08:00 604392 [Note] Event Scheduler: [root@localhost].[test0001.create_table_by_month1] event execution failed.

The above stored procedure is only the SQL of this blogger's online business environment. Please do not apply it directly. The loss caused has nothing to do with this blog post. This article is published here with the original intention of learning and communication, and is only for reference for everyone's learning and communication.

This concludes this article about the steps to create a table by month using a stored procedure in MySQL. For more information about creating a table by month in MySQL, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of creating, calling and managing MySQL stored procedures
  • Introduction to query commands for MySQL stored procedures
  • MySQL stored procedure in, out and inout parameter examples and summary
  • Detailed steps to modify MySQL stored procedures
  • Using cursor loop to read temporary table in Mysql stored procedure
  • Mysql modify stored procedure related permissions issue
  • In-depth explanation of MySQL stored procedures (in, out, inout)
  • A brief discussion on MySql views, triggers and stored procedures
  • Detailed example of using if statement in mysql stored procedure
  • Analysis of the advantages and disadvantages of MySQL stored procedures

<<:  Use of Linux stat command

>>:  Implementation of clicking through the transparent area of ​​​​irregular forms in Electron

Recommend

Detailed tutorial on installing nvidia driver + CUDA + cuDNN in Ubuntu 16.04

Preparation 1. Check whether the GPU supports CUD...

Detailed process of using Vscode combined with docker for development

Preface Using Docker and VS Code can optimize the...

The difference between docker run and start

The difference between run and start in docker Do...

Solution to the problem that Centos8 cannot install docker

Problem [root@zh ~]# [root@zh ~]# [root@zh ~]# yu...

How to install pyenv under Linux

Prerequisites Need to install git Installation St...

VUE introduces the implementation of using G2 charts

Table of contents About G2 Chart use Complete cod...

CSS to achieve scrolling image bar example code

On some websites, you can often see some pictures...

Linux Dig command usage

Dig Introduction: Dig is a tool that queries DNS ...

What do CN2, GIA, CIA, BGP and IPLC mean?

What is CN2 line? CN2 stands for China Telecom Ne...

Differences and usage examples of for, for...in, for...of and forEach in JS

for loop Basic syntax format: for(initialize vari...

JavaScript quickly implements calendar effects

This article example shares the specific code of ...

Detailed explanation of the pitfalls of mixing npm and cnpm

Table of contents cause reason Introduction to NP...

Example of Vue transition to achieve like animation effect

Table of contents Results at a Glance Heart Effec...