Solved

drop all the tables in a database

Posted on 2016-07-15
5
57 Views
Last Modified: 2016-07-18
I need a script to drop all the tables in a database. What would be the easiest way to do that?
0
Comment
Question by:vbnetcoder
5 Comments
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41713142
wouldn't it be easier to drop the database and recreate it?
1
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41713146
or you can try:
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"

Open in new window

0
 

Assisted Solution

by:vbnetcoder
vbnetcoder earned 0 total points
ID: 41713148
Eric you might be right on dropping the database
0
 
LVL 8

Accepted Solution

by:
Jason clark earned 500 total points
ID: 41713829
Try below script to drop all tables:

SELECT ' Drop table ' + s.NAME + '.' + 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

Open in new window


But remember If you have any foreign Keys defined between tables then first run the below query to disable all foreign keys present in your DB.

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

Open in new window

0
 
LVL 8

Expert Comment

by:Jose Torres
ID: 41717390
Remember by dropping the database you loose all objects (views, stored procedures.....)
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question