Update:
The same solution implemented within a store procedure with SQL using EXECUTE in a loop over a cursor with the tables to be truncated.
This store procedure expects a table named excepciones
with the list of tables that should not be truncated in a field called nombre_tabla
, the list of tables is taken from the system table information_schema.tables
It would be more or less like this:
CREATE PROCEDURE truncateAlgunas() BEGIN
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE nombreTabla VARCHAR(64);
DECLARE cur CURSOR FOR
SELECT table_name
FROM information_schema.tables
WHERE table_name NOT IN (SELECT nombreTabla FROM excepciones);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE;
OPEN cur;
truncateLoop: LOOP
FETCH cur INTO nombreTabla;
IF done THEN
LEAVE truncateLoop;
END IF;
PREPARE statement FROM CONCAT("TRUNCATE TABLE ", nombreTabla);
EXECUTE statement;
DEALLOCATE PREPARE statement;
END LOOP truncateLoop;
CLOSE cur;
END
And then you just run the store procedure. This is the same as I said before but implemented in mysql.
Note: I could not prove it, but it should work without major changes.
Previous answer
As far as you can not use parameters for the names of the tables (or columns) (eg: TRUNCATE TABLE @tablename
), so focus it discard.
A possible solution would be, using any other language, and by hand concatenate the name of the table to the statement truncate table
.
List<String> tablas = { "a", "b", "c" };
List<String> excepciones = { "b" };
String sentencia;
for(var tabla in tablas) {
if (!excepciones.contains(tabla)) {
sentencia += "TRUNCATE TABLE " + tabla + ";";
}
}
mySqlConnection.execute(sentencia);
This could also be done using SQL. Also, depending on the origin (reliability) of the list of tables and exceptions, you should check the value of tabla
by control characters to avoid sql injection .
More info at this post from OS in English