繁体   English   中英

截断所有匹配名称模式的表

[英]TRUNCATE all tables matching name pattern

这是我根据答案使用的sql:

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;

但是我收到此错误, Access denied for user 'root'@'%' to database 'information_schema' 我究竟做错了什么? 似乎对其他用户有效

您试图在“ information_schema”数据库上执行此语句。 阅读有关此数据库的更多信息[ https://dev.mysql.com/doc/refman/5.7/zh-CN/information-schema.html]

您不应该在information_schema数据库上运行语句(除非您真的知道自己在做什么)。 该数据库用作指示服务器如何运行的“元”存储库。 很有可能您不需要触摸它,如果这样做,您很可能会弄乱服务器。

这里已经回答了。 [ #1044-用户'root'@'localhost'对数据库'information_schema'的访问被拒绝

上面的限制:仅当该语句返回的表数大于1(对于1个以上的表)时,此查询才有效,您将需要在迭代中使用它。

为了使所有与该模式匹配的表都能使用,我们需要使用存储过程。

请更改程序名称

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM