如何使用一个 SQL 查询从数据库中删除所有表? [英] How to drop all tables from a database with one SQL query?
本文介绍了如何使用一个 SQL 查询从数据库中删除所有表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不想输入所有表的名称来删除所有表.一次查询可以吗?
I don't want to type all tables' name to drop all of them. Is it possible with one query?
推荐答案
使用 INFORMATION_SCHEMA.TABLES 视图以获取表列表.在 select 语句中生成 Drop 脚本并使用动态 SQL 将其删除:
Use the INFORMATION_SCHEMA.TABLES view to get the list of tables. Generate Drop scripts in the select statement and drop it using Dynamic SQL:
DECLARE @sql NVARCHAR(max)=''
SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Exec Sp_executesql @sql
Sys.Tables 版本
DECLARE @sql NVARCHAR(max)=''
SELECT @sql += ' Drop table ' + QUOTENAME(s.NAME) + '.' + QUOTENAME(t.NAME) + '; '
FROM sys.tables t
JOIN sys.schemas s
ON t.[schema_id] = s.[schema_id]
WHERE t.type = 'U'
Exec sp_executesql @sql
注意:如果您在表之间定义了任何外键
,则首先运行以下查询以禁用所有外键
存在于您的数据库中.
Note: If you have any foreign Keys
defined between tables then first run the below query to disable all foreign keys
present in your database.
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
更多信息,在此处查看.
这篇关于如何使用一个 SQL 查询从数据库中删除所有表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文