如何从Microsoft SQL Server Management Studio中删除数据库中的所有表?是否可以使用一个查询?
我不想单击单个表或在查询中键入单个表的名称以删除它们。
答案 0 :(得分:1)
以下是我有时使用的内容:
DECLARE @T NVARCHAR(255)
, @S NVARCHAR(255)
, @Type VARCHAR(255)
, @SQL NVARCHAR(MAX)
EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
DECLARE crs CURSOR FAST_FORWARD
FOR
SELECT QUOTENAME(T.TABLE_SCHEMA)
, QUOTENAME(T.TABLE_NAME)
, T.TABLE_TYPE
FROM INFORMATION_SCHEMA.TABLES T
-- Add where clause if you don't want to clear all schema's, or want to keep some tables.
OPEN crs
FETCH NEXT FROM crs INTO @S, @T, @Type
WHILE @@FETCH_STATUS = 0
BEGIN
IF @Type = 'BASE TABLE'
SET @SQL = CONCAT(N'DROP TABLE ', @S, '.', @T)
IF @Type = 'VIEW'
SET @SQL = CONCAT(N'DROP VIEW ', @S, '.', @T)
EXEC sys.sp_executesql @SQL
FETCH NEXT FROM crs INTO @S, @T, @Type
END
CLOSE crs
DEALLOCATE crs