Mysql
 sql >> Database >  >> RDS >> Mysql

Come posso troncare tutte le tabelle da un database MySQL?

Ok, l'ho risolto da solo, ecco la procedura memorizzata :)

BEGIN
    DECLARE done BOOLEAN DEFAULT FALSE; 
    DECLARE truncatestmnt TEXT; -- this is where the truncate statement will be retrieved from cursor

    -- This is the magic query that will bring all the table names from the database
    DECLARE c1 CURSOR FOR SELECT Concat('TRUNCATE TABLE ', TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA = "@DatabaseName";
    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE; 

    OPEN c1;

    c1_loop: LOOP
    FETCH c1 INTO truncatestmnt;
    IF `done` THEN LEAVE c1_loop; END IF;
        SET @x = truncatestmnt;
        PREPARE stm1 FROM @x;
        EXECUTE stm1;
    END LOOP c1_loop; 

    CLOSE c1;
END

Quello che sto facendo è chiamare tutte le tabelle dal database specificato, questo aiuterà se le tabelle all'interno del database specificato non hanno schemi da seguire.

Quindi chiamando DECLARE c1 CURSOR FOR SELECT Concat('TRUNCATE TABLE ', TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES WHERE INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA = "@DatabaseName"; e salvando i risultati in un cursore posso recuperare tutti i TRUNCATE TABLE x istruzioni generate dalla quantità "n" di tabelle all'interno del database specificato, quindi semplicemente preparando ed eseguendo ogni istruzione nel cursore troncherà tutte le tabelle all'interno del database specificato.

Spero che questo aiuti anche qualcun altro :)

Alessio