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


当前回答

MS SQL Server 2005+(删除打印以实际执行…)

EXEC sp_MSforeachtable 'PRINT ''TRUNCATE TABLE ?'''

如果您的数据库平台支持INFORMATION_SCHEMA视图,则获取以下查询的结果并执行它们。

SELECT 'TRUNCATE TABLE ' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

试试MySQL:

SELECT Concat('TRUNCATE TABLE ', TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES

在Concat中添加一个分号可以使它更容易使用,例如在mysql工作台中使用。

SELECT Concat('TRUNCATE TABLE ', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES

其他回答

溶液(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

使用它并形成查询

SELECT Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';') 
FROM INFORMATION_SCHEMA.TABLES where  table_schema in (db1,db2)
INTO OUTFILE '/path/to/file.sql';

现在使用this来使用这个查询

mysql -u username -p </path/to/file.sql

如果你得到这样的错误

ERROR 1701 (42000) at line 3: Cannot truncate a table referenced in a foreign key constraint

最简单的方法是在文件顶部添加这一行

SET FOREIGN_KEY_CHECKS=0;

也就是说,我们不想在遍历这个文件时检查外键约束。

它将截断数据库db1和bd2中的所有表。

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

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

这将输出截断所有表的命令:

SELECT GROUP_CONCAT(Concat('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME) SEPARATOR ';') FROM INFORMATION_SCHEMA.TABLES where table_schema in ('my_db');

我觉得最上面的答案太棒了。但是,当你有一个经过身份验证的MySQL数据库用户时,它就失败了。

这是建立在我链接的顶部答案之上的解决方案。此解决方案安全地处理身份验证,而无需:

为每个表输入密码 担心你的密码泄露到某个地方 对其他MySQL cnf文件(~/.my.cnf)的副作用要了解更多关于这些文件的详细信息,请查看答案底部的参考资料部分。

1. 创建本地。my.cnf文件

vi .temp.my.cnf
[client]
user=<admin_user_goes_here>
password=<admin_password_goes_here>

2. 截断或删除所有表

2.截断所有表(仅为空)

mysql --defaults-extra-file=.temp.my.cnf -Nse 'show tables' <db_name_goes_here> | while read table; do mysql --defaults-extra-file=.temp.my.cnf -e "truncate table $table" <db_name_goes_here>; done

2.B删除所有表(完全删除)

mysql --defaults-extra-file=.temp.my.cnf -Nse 'show tables' <db_name_goes_here> | while read table; do mysql --defaults-extra-file=.temp.my.cnf -e "drop table $table" <db_name_goes_here>; done

3.清理

删除用户密码文件

rm -rf .temp.my.cnf

资源:

https://rtcamp.com/tutorials/mysql/mycnf-preference/ https://dev.mysql.com/doc/refman/8.0/en/option-files.html https://dev.mysql.com/doc/refman/8.0/en/option-file-options.html#option_general_defaults-extra-file