Return to Snippet

Revision: 72560
at September 22, 2017 20:03 by gowthamcmv


Initial Code
CREATE PROCEDURE delete_if_exists(IN tbl CHAR(255),IN dbn char(255)) -- tbl=table_name, dbn=database_name
BEGIN
    IF @tbl IN (select table_name from information_schema.tables where table_schema = dbn)
    THEN
        SET @query = CONCAT("TRUNCATE TABLE ", @dbn, ".", @tbl);
        PREPARE stmt FROM @query;
        EXECUTE stmt;
    END IF;
END ;

Initial URL


Initial Description
Truncate or Delete a table only if it exists can not be done with a single line query. 
We can achieve it with dynamic querying with a stored procedure.

Initial Title
TRUNCATE table IF EXISTS

Initial Tags


Initial Language
MySQL