Using A Stored Procedure drop all Tables In A MySQL Database - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Sunday, June 17, 2012

Using A Stored Procedure drop all Tables In A MySQL Database

Using an engine like InnoDB, which enforces referential integrity through the use of foreign keys, poses a little problem when deleting a table whose field(s) act as foreign keys in other table(s). Dropping an entire database may seem like a convenient approach to use, but will not be an option to users who do not have database creation privileges on the database server, and for those who would want to preserve other objects in the database like views, functions, stored prodecures, etc.

Deleting interconnected tables in a database can be a little frustrating, but the solution is that simple, suppress foreign key checks, if necessary, and delete the tables of interest.
Implementing a solution in the database through the use of a stored procedure is show below.

DROP PROCEDURE IF EXISTS procDropAllTables $$

CREATE PROCEDURE procDropAllTables()

     BEGIN
DECLARE table_name VARCHAR(255);
DECLARE end_of_tables INT DEFAULT 0;

DECLARE cur CURSOR FOR 
SELECT t.table_name 
FROM information_schema.tables t 
WHERE t.table_schema = DATABASE() AND t.table_type='BASE TABLE';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET end_of_tables = 1;

SET FOREIGN_KEY_CHECKS = 0;
OPEN cur;

tables_loop: LOOP
FETCH cur INTO table_name;

IF end_of_tables = 1 THEN
LEAVE tables_loop;
END IF;

SET @s = CONCAT('DROP TABLE IF EXISTS ' , table_name);
PREPARE stmt FROM @s;
EXECUTE stmt;

END LOOP;
CLOSE cur;
SET FOREIGN_KEY_CHECKS = 1;
END

Now, let's drop all the tables by calling our stored procedure as show below.

CALL procDropAllTables();

The above procedure can be tweaked if table deletion is not desired, but should be rather emptied by changing the highlighted line to

SET @s = CONCAT('DELETE FROM ' , table_name);

This is only one of the approaches that could be used to solve the problem, but they all basically work on the same premise that foreign key checks MUST BE disabled.


I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too. 

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.


No comments:

Post a Comment