MySQL stored procedure to delete the timing table

In industrial monitoring inside, the need for daily data, record, after a long time, MySQL database easily explode. At this time, if allowed to conduct a clearance of previous data, record data only within a few months.

$ DELIMITER
the DROP PROCEDURE IF EXISTS p_clearOldData;
/ *
g_date_limit time limit, such as 2019_08, the table is deleted before the time
length g_date_length time format, such as time suffix 2019_08, the transmission should here. 7 
* /
Create PROCEDURE p_clearOldData (in g_date_limit VARCHAR (30), in g_date_length int)
the begin
    / * query to the table name * /
    DECLARE g_table VARCHAR (100);

    / * The table name query to the time corresponding to the suffix * /
    the DECLARE g_date VARCHAR (30) the DEFAULT '';

    / * Define done, for use out of the loop * /
    the DECLARE DONE 'bit the DEFAULT 0;

    /*声明游标*/
    DECLARE g_cursor CURSOR FOR select TABLE_NAME from INFORMATION_SCHEMA.TABLES  where TABLE_SCHEMA='tt_abc' and TABLE_NAME like 't_bk001_%';

    / * When the cursor query, the next one if not found, will be done is set to 1 for a REPEAT loop out * /
  the DECLARE the CONTINUE the FOR HANDLER the NOT FOUND the SET done = 1;

    / * * Pending dynamic SQL /
    SET @v_full_sql: = '';

    / * Open the cursor * /
    Open g_cursor;

    REPEAT

        FETCH g_cursor into g_table;

        set g_date = right(g_table, g_date_length);

        if g_date < g_date_limit then

            set @v_full_sql = CONCAT('drop table if exists ',g_table);

            / * This precompiled dynamic sql, and stored in stmt * /
            the PREPARE stmt from @v_full_sql;

            / * Perform this dynamic sql, the role of this dynamic sql, delete table * /
            the Execute stmt;   

            / * Release this resource * /
            DEALLOCATE PREPARE stmt;

        end if;

    / * End of a repeat loop * /
    the UNTIL DONE the REPEAT the END;

    / * Close the cursor * /
    Close g_cursor;

select 'OK';

end $
delimiter;

In the MySQL database, the test:

CREATE TABLE `t_bk001_2019_02` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Execute the script:

call p_clearOldData('2019_03', 7);

You will find that the table really is deleted, and the other table has not been affected.

In the case where the background can not send packets, and the scheduled tasks can be stored mysql procedure, to achieve timing table delete operation.

However, if in this way, also we need to change this storage process, or re-create a stored procedure, this procedure is stored as a package with no parameters.

*Note:

The above operation is not recommended accomplishes this task by the timing and stored procedures in MySQL, recommended by the timing of the background task execution table deletion operations.

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160476.htm