1

Unlike the other posts about the task "delete all tables", this question is specifically about using SqlCommand to access the database.

A coworker is facing the problem that no matter how it attempts it, he can't delete all tables from a database via SqlCommand. He states that he can't perform such action as long as there is an active connection - the connection by the SqlCommand itself.

I believe this should be possible and easy, but I don't have much of a clue about databases so I came here to ask. It would be awesome if you could provide a short code example in C# (or any .NET language, for that matter).

If you require additional information, just leave a comment.

1
  • (He's not using SO, that's why I ask in his stead.) Commented Apr 8, 2010 at 10:35

2 Answers 2

1

If you want to delete the tables without dropping the database you can also use the following command:

exec sp_MSforeachtable 'DROP TABLE ?'

Beware that you have to disable/delete all Foreign Key Constraints first, or it will most likely fail.

Sign up to request clarification or add additional context in comments.

4 Comments

And how you disable/delete all Foreign Key Constraints first?
You can disable them with EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL".
but they will still be there :/
The question was including "how to disable" them, not necessarily how to delete them. There is an old article on MSDN that shows how to drop all constraints and foreign keys: tinyurl.com/lz8fpzh
0

You either need to issue a DROP DATABASE command - connect to the "master" database on the server in question, and then issue a

DROP DATABASE (your database)

command.

Something like:

using (SqlConnection con = new SqlConnection("server=yourserver;database=master;integrated security=SSPI"))
{
    using (SqlCommand cmd = new SqlCommand("DROP DATABASE (your database)", con))
    {
        try
        {
            con.Open();
            int returnValue = cmd.ExecuteNonQuery();
            con.Close();
        }
        catch (Exception exc)
        {
            string errorMsg = string.Format("{0}: {1}", exc.GetType().FullName, exc.Message);   
        }
    }
}

Or then you need to iterate over all tables - there's no single command to drop all tables at once. Also, when dropping tables, you might need to drop constraints and indexes first.

Dropping everything isn't exactly an easy job!

1 Comment

alter database YourDatabase set offline with rollback immediate ; alter database YourDatabase set online with rollback immediate ; drop database YourDatabase can be useful as well if other connections might be using the DB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.