Want to truncate a table if it exists:
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'mytable') TRUNCATE mytable
Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'mytable') ' at line 1
I tried also to add THEN after ) but the problems seems to be at IF.
TRUNCATE is faster than DELETE , as it doesn't scan every record before removing it. TRUNCATE TABLE locks the whole table to remove data from a table; thus, this command also uses less transaction space than DELETE .
You need the two statements below to do that:
create table if not exists <mytable>;
truncate table <mytable>;
So I had a similar issue, and to resolve it, I created this procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `truncate_if_exist`$$
CREATE PROCEDURE `truncate_if_exist`(IN tbl_name VARCHAR(150) )
BEGIN
IF EXISTS( SELECT 1 FROM information_schema.TABLES WHERE table_name = tbl_name AND table_schema = DATABASE()) THEN
SET @query = CONCAT('TRUNCATE ', tbl_name);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END $$
DELIMITER ;
And then called it for each table that I wanted to truncate
for example:
CALL truncate_if_exist('users');
CALL truncate_if_exist('random_tmp_table');
Obviously, if the table does not exist, it will not run the TRUNCATE
command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With