TRUNCATE table IF EXISTS


/ Published in: MySQL
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. CREATE PROCEDURE delete_if_exists(IN tbl CHAR(255),IN dbn char(255)) -- tbl=table_name, dbn=database_name
  2. IF @tbl IN (select table_name from information_schema.tables where table_schema = dbn)
  3. SET @query = CONCAT("TRUNCATE TABLE ", @dbn, ".", @tbl);
  4. PREPARE stmt FROM @query;
  5. EXECUTE stmt;
  6. END ;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.