刪除所有表的PROCEDURE的方法及代碼

字號:

一起來看以下刪除所有表的PROCEDURE的方法及代碼。
    CREATE PROCEDURE proc_drop_all_tables()
    begin
    declare v_tablename varchar(50);
    declare v_constname varchar(50);
    declare flag int default 0;
    --定義一個游標,尋找所有的外鍵
    declare cur_constraint cursor for select table_name,constraint_name
    from information_schema.table_constraints
    where constraint_type='FOREIGN KEY'
    and table_schema=(select database());
    --定義一個游標,尋找所有表
    declare cur_table cursor for select table_name from information_schema.tables
    where table_type='BASE TABLE' and table_schema=( select database());
    --定義一個游標,尋找所有視圖
    declare cur_view cursor for select table_name from information_schema.tables
    where table_type='VIEW' and table_schema=( select database());
    declare continue handler for not found
    set flag=1;
    --循環(huán)去刪除所有外鍵
    open cur_constraint;
    repeat
    fetch cur_constraint into v_tablename,v_constname;
    if flag= 0 then
    set @v_sql = concat('alter table ',v_tablename,' drop foreign key ',v_constname);
    prepare stmt from @v_sql;
    execute stmt;
    end if;
    until flag=1
    end repeat;
    close cur_constraint;
    set flag=0;
    --循環(huán)去刪除所有視圖
    open cur_view;
    repeat
    fetch cur_view into v_tablename;
    if flag=0 then
    set @v_sql = concat('drop view ',v_tablename);
    prepare stmt from @v_sql;
    execute stmt;
    end if;
    until flag=1
    end repeat;
    set flag=0;
    close cur_view;
    --循環(huán)去刪除所有表
    open cur_table;
    repeat
    fetch cur_table into v_tablename;
    if flag = 0 then
    set @v_sql = concat('drop table ',v_tablename);
    prepare stmt from @v_sql ;
    execute stmt ;
    end if;
    until flag=1
    end repeat;
    deallocate prepare stmt;
    close cur_table;
    end;