如何使用SqlCommand删除数据库中的所有表? [英] How do I delete all tables in a database using SqlCommand?
问题描述
与其他有关任务删除所有表的帖子不同,该问题专门用于使用 SqlCommand
访问数据库。
Unlike the other posts about the task "delete all tables", this question is specifically about using SqlCommand
to access the database.
一个同事面临的问题是,无论如何尝试,他都无法通过SqlCommand从数据库中删除所有表。他指出,只要存在活动连接(即SqlCommand本身的连接),他就无法执行此类操作。
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.
我相信这应该是可能且容易的,但是我对数据库了解不多,所以我来这里问。如果您可以使用C#(或任何.NET语言)提供一个简短的代码示例,那就太棒了。
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.
推荐答案
您要么需要发出DROP DATABASE命令-连接到相关服务器上的 master数据库,然后发出
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)
命令。
类似以下内容:
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!
这篇关于如何使用SqlCommand删除数据库中的所有表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!