Check if a SQL table exists

后端 未结 9 2349
北海茫月
北海茫月 2020-12-01 06:30

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 sql         


        
9条回答
  •  盖世英雄少女心
    2020-12-01 06:43

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

提交回复
热议问题