是否存在在一次操作中截断数据库中所有表的查询(命令)?我想知道我是否可以用一个查询做到这一点。


当前回答

溶液(1)

mysql> select group_concat('truncate',' ',table_name,';') from information_schema.tables where table_schema="db_name" into outfile '/tmp/a.txt';
mysql> /tmp/a.txt;

溶液2)

- Export only structure of a db
- drop the database
- import the .sql of structure 

——编辑----

earlier in solution 1, i had mentioned concat() instead of group_concat() which would have not returned the desired result

其他回答

SET FOREIGN_KEY_CHECKS = 0;

SELECT @str := CONCAT('TRUNCATE TABLE ', table_schema, '.', table_name, ';')
FROM   information_schema.tables
WHERE  table_type   = 'BASE TABLE'
  AND  table_schema IN ('db1_name','db2_name');

PREPARE stmt FROM @str;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;

SET FOREIGN_KEY_CHECKS = 1;

以这种方式使用phpMyAdmin:

Database View => Check All (tables) =>空

如果你想忽略外键检查,你可以取消选中下面的复选框:

[]启用外键检查

您至少需要运行4.5.0或更高版本才能获得此复选框。

它不是MySQL CLI-fu,但是,嘿,它工作!

我发现TRUNCATE表..外键约束有问题,即使在NOCHECK约束ALL之后,所以我使用DELETE FROM语句代替。这意味着身份种子不会被重置,你总是可以添加一个DBCC CHECKIDENT来实现这一点。

我使用下面的代码打印到消息窗口的sql截断数据库中的所有表,然后运行它。这只会让犯错变得更难。

EXEC sp_MSforeachtable 'PRINT ''ALTER TABLE ? NOCHECK CONSTRAINT ALL'''
EXEC sp_MSforeachtable 'print ''DELETE FROM ?'''
EXEC sp_MSforeachtable 'print ''ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'''

下面是一个截断本地数据库中所有表的过程。

如果它不起作用,请告诉我,我会删除这个答案。

未测试的

CREATE PROCEDURE truncate_all_tables()
BEGIN

   -- Declare local variables
   DECLARE done BOOLEAN DEFAULT 0;
   DECLARE cmd VARCHAR(2000);

   -- Declare the cursor
   DECLARE cmds CURSOR
   FOR
   SELECT CONCAT('TRUNCATE TABLE ', TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES;

   -- Declare continue handler
   DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

   -- Open the cursor
   OPEN cmds;

   -- Loop through all rows
   REPEAT

      -- Get order number
      FETCH cmds INTO cmd;

      -- Execute the command
      PREPARE stmt FROM cmd;
      EXECUTE stmt;
      DROP PREPARE stmt;

   -- End of loop
   UNTIL done END REPEAT;

   -- Close the cursor
   CLOSE cmds;

END;

这对我很管用。修改数据库、用户名和密码。

mysql -Nse 'show tables' -D DATABASE -uUSER -pPWD | while read table; do echo "SET FOREIGN_KEY_CHECKS = 0;drop table \`$table\`;SET FOREIGN_KEY_CHECKS = 1;"; done | mysql DATABASE -uUSER -pPWD