通过 C# 和 SMO 检查并删除现有表

发布于 2024-07-21 09:00:38 字数 213 浏览 5 评论 0原文

我正在尝试按名称查找 SQL 表,如果存在则删除它。 这一切都需要使用 SMO 在 C# 中完成。

更复杂的是,该表还有一个“dbo”以外的模式。

最终该表将通过 SMO 重新创建(我可以正常工作),但我必须确保它不存在,然后才能重新创建它。

我看到的所有示例似乎都是在相同的上下文中创建然后删除表。 就我而言,该表将在上一个会话中创建并填充。

I am trying to look for a SQL table by name and if it exists drop it. This all needs to be done in C# using SMO.

To complicate it a bit more the table also has a schema other then "dbo".

Ultimatly the table will be recreated via SMO (I have this working) but I have to make sure it is not there before I can recreate it.

All of the examples that I have seen seem to be creating and then dropping the table all in the same context. In my case the table will have been created and populated in a previous session.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一抹淡然 2024-07-28 09:00:38
var connection = new SqlConnection(connectionString);
var server = new Server(new ServerConnection(connection));

db = server.Databases["YourFavDB"];

db.Tables["YourHatedTable"].Drop();
var connection = new SqlConnection(connectionString);
var server = new Server(new ServerConnection(connection));

db = server.Databases["YourFavDB"];

db.Tables["YourHatedTable"].Drop();
滥情空心 2024-07-28 09:00:38

我认为最好的方法是:

Microsoft.SqlServer.Management.Smo.Database myDataBase = myServer.Databases["myDataBaseName"];
bool tableExists= myDataBase.Tables.Contains("myTable");
if (tableExists)
{
   myDataBase.Tables["myTable"].Drop();
}

I think the best approach would be:

Microsoft.SqlServer.Management.Smo.Database myDataBase = myServer.Databases["myDataBaseName"];
bool tableExists= myDataBase.Tables.Contains("myTable");
if (tableExists)
{
   myDataBase.Tables["myTable"].Drop();
}
余生再见 2024-07-28 09:00:38

难道您不能将 DROP TABLE 语句包装在 try/catch 块中,并丢弃发生的任何错误吗?

不管怎样,判断表是否存在的sql是:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))

Couldn't you just wrap your DROP TABLE statement in a try/catch block, and discard any errors that occur?

Anyway, the sql to determine if a table exists is:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))
笙痞 2024-07-28 09:00:38

第一个问题是,为什么不能用 DDL 删除并重新创建?

并回答你的问题:

Table table = new Table(myDatabase, "MyTable", "MySchema");

First question is, why can you not drop and recreate with DDL?

And in answer to your question:

Table table = new Table(myDatabase, "MyTable", "MySchema");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文