Posted By

gowthamcmv on 09/22/17


Tagged

delete truncate DML


Versions (?)

TRUNCATE table IF EXISTS


 / Published in: MySQL
 

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.

  1. CREATE PROCEDURE delete_if_exists(IN tbl CHAR(255),IN dbn CHAR(255)) -- tbl=table_name, dbn=database_name
  2. BEGIN
  3. IF @tbl IN (SELECT table_name FROM information_schema.tables WHERE table_schema = dbn)
  4. THEN
  5. SET @query = CONCAT("TRUNCATE TABLE ", @dbn, ".", @tbl);
  6. PREPARE stmt FROM @query;
  7. EXECUTE stmt;
  8. END IF;
  9. END ;

Report this snippet  

You need to login to post a comment.