Apply mysql query to each table in a database

后端 未结 2 1459
一个人的身影
一个人的身影 2021-01-18 09:37

is there a way to apply a query to each table in a mysql database?

Something like

SELECT count(*) FROM {ALL TABLES}
-- gives the number of count(*) i         


        
2条回答
  •  轮回少年
    2021-01-18 09:50

    select sum(table_rows) as total_rows
    from information_schema.tables
    where table_schema = 'your_db_name'
    

    beware this is just an approximate value

    In order to delete the contents of all your tables you can do something like this

    select concat('truncate ',table_name,';')
    from information_schema.tables
    where table_schema = 'your_db_name'
    

    Then run the output of this query.

    UPDATE.

    This is a stored procedure to apply truncate table to all tables in a specific database

    delimiter //
    drop procedure if exists delete_contents //
    create procedure delete_contents (in db_name varchar(100))
    begin
    declare finish int default 0;
    declare tab varchar(100);
    declare cur_tables cursor for select table_name from information_schema.tables where table_schema = db_name and table_type = 'base table';
    declare continue handler for not found set finish = 1;
    open cur_tables;
    my_loop:loop
    fetch cur_tables into tab;
    if finish = 1 then
    leave my_loop;
    end if;
    
    set @str = concat('truncate ', tab);
    prepare stmt from @str;
    execute stmt;
    deallocate prepare stmt;
    end loop;
    close cur_tables;
    end; //
    delimiter ;
    
    call delete_contents('your_db_name');
    

提交回复
热议问题