Click here to Skip to main content
15,897,187 members
Articles / Database Development / SQL Server
Tip/Trick

Drop all the tables in a database

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
31 Jan 2012CPOL 51K   3   3
Drop all the tables in a database(give the database name and table name in the below query).
SQL
--Drop all the table in the database
USE DATABASE
GO
DECLARE @tname VARCHAR(150)
DECLARE @strsql VARCHAR(300)

SELECT @tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' and [name] like N'TableName%' ORDER BY [name])

WHILE @tname IS NOT NULL
BEGIN
    SELECT @strsql = 'DROP TABLE [dbo].[' + RTRIM(@tname) +']'
    EXEC (@strsql)
    PRINT 'Dropped Table : ' + @tname
    SELECT @tname = (SELECT TOP 1 [name] FROM sys.objects WHERE [type] = 'U' AND [name] like N'TableName%'  AND [name] > @tname ORDER BY [name])
END

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
.Net Programmer

Comments and Discussions

 
QuestionSQL Server 2008 Tried the following Pin
Timotheos10-Nov-12 1:16
Timotheos10-Nov-12 1:16 
GeneralFirst and foremost, thanks for taking the time to share. A f... Pin
Pablo Aliskevicius31-Jan-12 20:01
Pablo Aliskevicius31-Jan-12 20:01 
SuggestionConstraints Pin
yannduran31-Jan-12 14:03
yannduran31-Jan-12 14:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.