简体   繁体   English

删除表的最快方法(如果存在)

[英]Fastest Way To Delete Table (If Exists)

I am using C# to connect to an access database and checking if a table exists in that database. 我正在使用C#连接到Access数据库,并检查该数据库中是否存在表。 This is the syntax I am using, but for a few databases that have lots of tables in them it takes quite some time to execute. 这是我正在使用的语法,但是对于其中有很多表的一些数据库,执行它需要花费一些时间。 Is their a faster way to do this as speed is the most important thing for this procedure? 他们是这样做的更快方法,因为速度是此过程中最重要的事情?

string[] tableNames = new string[4] { "One", "Two", "Three", "Four" };
for (int q = tableNames.GetLowerBound(0); q <= tableNames.GetUpperBound(0); q++)
{
  foreach (DAO.TableDef tabledef in dd.TableDefs)
  {
    string strtable = tableNames[q];
    if (tabledef.Name == strtable) { found = true; }
    if (found) { dd.TableDefs.Delete(strtable); } 
  }
}

For any future travelers who might stumble upon this, this was my final syntax that I used --- Exponentially faster!!! 对于可能会偶然发现此问题的任何未来旅行者,这是我使用的最终语法---指数级提高!!!

Last EDIT --- I changed the Execute statement to be encapsulated in a try/catch block as if the table name that is listed in the array does not actually exist it will throw an error. 上一次编辑---我将Execute语句更改为封装在try/catch块中,就好像数组中列出的表名实际上不存在一样,它将引发错误。

System.Data.OleDb.OleDbConnection oleconn = new   OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + PathToDatabase" + ".mdb;");
oleconn.Open();
string[] tableNames = new string[4] { "One", "Two", "Three", "Four" };
for (int q = tableNames.GetLowerBound(0); q <= tableNames.GetUpperBound(0); q++)
{
  System.Data.OleDb.OleDbCommand cmd = new OleDbCommand("DROP TABLE " + tableNames[q], oleconn);
  try { cmd.ExecuteNonQuery(); }
  catch {}
}
oleconn.Close();

Reverse the loops (pseudo code): 反转循环(伪代码):

foreach (DAO.TableDef tabledef in dd.TableDefs)
{
  if (tabledef.Name in tablearray )
  { 
    dd.TableDefs.Delete(strtable); 
  } 
}

I think instead of checking in C# application run following query with your ado.net. 我认为与其签入C#应用程序而不是通过ado.net查询运行。

IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL 
     DROP TABLE 'mytablename'

Because it will load meta data when you use ado.net instead of that execute simple query with execute non query. 因为当您使用ado.net而不是通过执行非查询执行简单查询时,它将加载元数据。

You can use Drop Table for deleting table.. and its syntax is 您可以使用Drop Table删除表。其语法为

   if exists (select * from login where name = 'prishu' and pass='prishu')
    drop table login

for more information use this link 有关更多信息,请使用此链接

check this link also 还要检查此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM