TRUNCATE all tables matching name pattern

空扰寡人 提交于 2019-12-25 08:38:57

问题


This is the sql i'm using based from this answer:

SET @pattern = '%_movielist';

SELECT concat('TRUNCATE TABLE ', GROUP_CONCAT(concat(TABLE_NAME)), ';')
INTO @truncatelike FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE @pattern;

SELECT @truncatelike;

PREPARE stmt FROM @truncatelike;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

but I get this error Access denied for user 'root'@'%' to database 'information_schema'. What am I doing wrong? It seems to work for other users


回答1:


You trying to execute this statement on "information_schema" database. Read more about this database [https://dev.mysql.com/doc/refman/5.7/en/information-schema.html]

You should not be running statements on the information_schema database (unless you REALLY know what you're doing). The database serves as a "meta" repository that dictates how the server operates. Chances are that you have no need to touch it and you'll likely brick your server if you do.

This is already answered here. [#1044 - Access denied for user 'root'@'localhost' to database 'information_schema'

Restriction to above: This query will work only if the no of table returned by the statement is 1 for more than 1 tables, you will require to use it in iteration.

To make this work for all the table matching the pattern we would require to use stored procedure.

Please change the Procedure name

CREATE PROCEDURE `new_procedure`()
BEGIN
-- Pattern to Match 
SET @pattern = '%_movielist';
-- Temporary Table to Store the Result of The Select Statement

CREATE TEMPORARY TABLE IF NOT EXISTS Table_ToBeTruncated 
    (
       Id int NOT NULL AUTO_INCREMENT,TableName varchar(100),
       PRIMARY KEY (id)
    );

-- Insert all the TableName  to be Truncated 
    insert Table_ToBeTruncated(TableName)
    SELECT distinct concat('TRUNCATE TABLE `', TABLE_NAME, '`;')
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME LIKE @pattern and TABLE_SCHEMA = 'movielist';

-- Declare a variable to count the no of records to be truncated.
SET @count=(Select count(*)from Table_ToBeTruncated);

-- Iterate the list 
WHILE @count> 0 DO

    -- Pick One table from the Temporary Table List;
    SELECT TableName into @truncatelike from Table_ToBeTruncated where ID= @count;

    -- Prepare the statement
    PREPARE stmt FROM @truncatelike;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    -- Decrease the counter.
    set @count = @count- 1;

END WHILE;

drop TEMPORARY TABLE IF EXISTS Table_ToBeTruncated ;

END


来源:https://stackoverflow.com/questions/44305115/truncate-all-tables-matching-name-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!