检查SQL表存在存在、SQL

2023-09-02 11:53:50 作者:无欲无求

什么是来检查表是否存在在一个SQL数据库在数据库独立的方式最好?

我想出了:

 布尔存在;
   常量字符串的SQLStatement = @SELECT COUNT(*)FROM my_table的;

   尝试
    {
       使用(的OdbcCommand CMD =新的OdbcCommand(的SQLStatement,myOdbcConnection))
       {
            cmd.ExecuteScalar();
            存在= TRUE;
       }
    }
    抓住
    {
        存在= FALSE;
    }
 

有没有更好的方式来做到这一点?当连接到数据库失败,这种方法是行不通的。我发现方式适用于Sybase,SQL服务器,甲骨文,但没有适用于所有数据库。

解决方案

 布尔存在;

尝试
{
    // ANSI SQL的方式。作品在PostgreSQL中,MSSQL,MySQL的。
    VAR CMD =新的OdbcCommand(
      选择的情况下,当存在((选择INFORMATION_SCHEMA.TABLES *在表格名='+ tableName值+)),则1否则为0结束);

    存在=(int)的cmd.ExecuteScalar()== 1;
}
抓住
{
    尝试
    {
        //其他RDBMS。优雅降级
        存在= TRUE;
        VAR cmdOthers =新的OdbcCommand(中选择1,从+ tableName值+,其中1 = 0);
        cmdOthers.ExecuteNonQuery();
    }
    抓住
    {
        存在= FALSE;
    }
}
 

如何查看SQL中已经存在的函数

What's the best way to check if a table exists in a Sql database in a database independant way?

I came up with:

   bool exists;
   const string sqlStatement = @"SELECT COUNT(*) FROM my_table";

   try
    {
       using (OdbcCommand cmd = new OdbcCommand(sqlStatement, myOdbcConnection))
       {
            cmd.ExecuteScalar();
            exists = true;
       }
    }
    catch
    {
        exists = false;
    }

Is there a better way to do this? This method will not work when the connection to the database fails. I've found ways for Sybase, SQL server, Oracle but nothing that works for all databases.

解决方案

bool exists;

try
{
    // ANSI SQL way.  Works in PostgreSQL, MSSQL, MySQL.  
    var cmd = new OdbcCommand(
      "select case when exists((select * from information_schema.tables where table_name = '" + tableName + "')) then 1 else 0 end");

    exists = (int)cmd.ExecuteScalar() == 1;
}
catch
{
    try
    {
        // Other RDBMS.  Graceful degradation
        exists = true;
        var cmdOthers = new OdbcCommand("select 1 from " + tableName + " where 1 = 0");
        cmdOthers.ExecuteNonQuery();
    }
    catch
    {
        exists = false;
    }
}