Check if a SQL table exists.

Posted by Carra on Stack Overflow See other posts from Stack Overflow or by Carra
Published on 2009-01-21T08:48:25Z Indexed on 2010/05/02 9:17 UTC
Read the original article Hit count: 240

Filed under:
|
|

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 (Exception ex)
        {
            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.

© Stack Overflow or respective owner

Related posts about sql

Related posts about c#