The mysql script clears the data in all tables under the current database and resets the auto-increment id

 

Note: After the actual Truncate table, the auto-increment id will automatically start from 1. The stored procedure here is for the integrity of the program and to set the auto-increment id more flexibly.

 

The picture below is in color, and the structure looks clear

Below is the original code

 

CREATE  PROCEDURE `reset_autoIncrement`()
begin

declare v_table_name varchar(100); -- @city fog custom variable
declare done int default false; -- @city fog custom control cursor loop variable, default false  
declare sql_for_select varchar(500);          

    
declare my_cursor cursor for 
    select  table_name 
    from information_schema.tables 
    where table_schema=database();

declare continue handler for not found set done = true; -- @city fog bind the control variable to the cursor, the cursor loop will automatically turn true 
open my_cursor; -- @city fog   open the cursor  
  
    myloop: loop -- @city fog start the loop body,

        fetch my_cursor into v_table_name; -- @city fog assigns the data sequence of the cursor's current read row to a custom variable

        set sql_for_select = concat("truncate table ", v_table_name);

        #select sql_for_select;   
        set @sql = sql_for_select;
        prepare stmt from @sql; -- @city fog preprocessing dynamic sql statement
        execute stmt ; -- @city fog execute sql statement #modify
        
        self-increment id
        set sql_for_select = concat( " alter table ", v_table_name," auto_increment = 1");  
        set @sql = sql_for_select;
        prepare stmt from @sql; -- @city fog preprocessing dynamic sql statement
        execute stmt ; --@city fog execute sql statement

        if done then -- @city fog judges whether to continue the loop  
             leave myloop; -- @city fog ends the loop  
        end if;  

  end loop myloop; -- @city fog end custom loop body  
    deallocate prepare stmt; -- @city fog release prepare


  close my_cursor; -- @city fog closes the cursor  

end

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325018179&siteId=291194637