Skip to content

Instantly share code, notes, and snippets.

@Marko-M
Last active August 14, 2018 02:51
Show Gist options
  • Save Marko-M/10931ff5e990431b5410 to your computer and use it in GitHub Desktop.
Save Marko-M/10931ff5e990431b5410 to your computer and use it in GitHub Desktop.
Stored procedure - drop all tables [MySQL]
DELIMITER //
CREATE PROCEDURE dropAllTables()
--
-- dropAllTables
-- Date: 2014-05-26
-- Author: Andrew Cassidy <[email protected]>
-- Author: Marko Martinović <[email protected]>
--
-- This Stored Procedure loops over the tables in the current database and
-- drops them.
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
BEGIN
-- Temporary variable for the table name
DECLARE tableName NVARCHAR(255);
-- Wheteher or not the cursor is finished looping over the table list
DECLARE done INT DEFAULT FALSE;
-- A cursor over the table list read from the MySQL information schema database
DECLARE tableCursor CURSOR FOR SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = (SELECT DATABASE());
-- Set up the error handler for breaking out of the loop reading the cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- Disable foreign key checks
SET FOREIGN_KEY_CHECKS = 0;
-- Open the cursor
OPEN tableCursor;
-- Start looping over the records in the cursor
read_loop: LOOP
-- Read the next item into our tableName variable
FETCH tableCursor INTO tableName;
-- If fecth failed (and the error handler set done), exit the loop
IF done THEN
LEAVE read_loop;
END IF;
-- Create the truncate query
SET @s = CONCAT('DROP TABLE ', tableName);
-- Prepare, execute and deallocate the truncate query
PREPARE dropStmt FROM @s;
EXECUTE dropStmt;
DEALLOCATE PREPARE dropStmt;
-- On to the next!
END LOOP;
-- Close the cursor, all should be cleaned up now
CLOSE tableCursor;
-- Enable foreign key checks
SET FOREIGN_KEY_CHECKS = 1;
END//
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment