Solved

drop all the tables in a database

Posted on 2016-07-15
5
53 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 69

Expert Comment

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

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 7

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

911 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

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now