Uncategorized

Drop all tables in database (WHILE version)

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON
GO

DECLARE @SchemaName NVARCHAR(128)
DECLARE @TableName NVARCHAR(128)
DECLARE @Stmt NVARCHAR(MAX)

DECLARE @TablesToDel TABLE ([SchemaName] NVARCHAR(128) NOT NULL,
							[TableName] NVARCHAR(128),
						    PRIMARY KEY ([SchemaName], [TableName]))

INSERT INTO @TablesToDel 
	( [SchemaName], [TableName])
SELECT [s].[name], [t].[name]
FROM [sys].[tables] AS [t] 
	INNER JOIN [sys].[schemas] AS [s]  ON [t].[schema_id] = [s].[schema_id]
WHERE [t].[type] IN ('U') AND [s].[name] IN (/*Fill list*/)
		
WHILE EXISTS (SELECT * FROM @TablesToDel)
BEGIN
    
	SELECT TOP(1)
		@SchemaName = [SchemaName],
		@TableName = [TableName]
	FROM @TablesToDel [td]
	ORDER BY [SchemaName], [td].[TableName]

	PRINT 'DROP TABLE ' + QUOTENAME(@SchemaName) + N'.' + QUOTENAME(@TableName) + ';' + CHAR(13) + 'GO'

	DELETE FROM @TablesToDel WHERE [SchemaName] = @SchemaName AND [TableName] = @TableName

END
GO