Created
August 19, 2019 16:43
-
-
Save Dillie-O/84327ddf22cde9046ff75ed8d53d3104 to your computer and use it in GitHub Desktop.
[Drop All Tables] Drops all tables in a given database #sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Drop all Primary Key constraints */ | |
DECLARE @name VARCHAR(128) | |
DECLARE @constraint VARCHAR(254) | |
DECLARE @SQL VARCHAR(254) | |
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME) | |
WHILE @name IS NOT NULL | |
BEGIN | |
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME) | |
WHILE @constraint is not null | |
BEGIN | |
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']' | |
EXEC (@SQL) | |
PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name | |
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME) | |
END | |
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME) | |
END | |
GO | |
/* Drop all tables */ | |
DECLARE @name VARCHAR(128) | |
DECLARE @SQL VARCHAR(254) | |
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name]) | |
WHILE @name IS NOT NULL | |
BEGIN | |
SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']' | |
EXEC (@SQL) | |
PRINT 'Dropped Table: ' + @name | |
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name]) | |
END | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment