Checking for and dropping an existing table via C# and SMO

女生的网名这么多〃 提交于 2019-12-10 13:24:12

问题


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.


回答1:


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");



回答2:


var connection = new SqlConnection(connectionString);
var server = new Server(new ServerConnection(connection));

db = server.Databases["YourFavDB"];

db.Tables["YourHatedTable"].Drop();



回答3:


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();
}



回答4:


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'))


来源:https://stackoverflow.com/questions/928346/checking-for-and-dropping-an-existing-table-via-c-sharp-and-smo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!