tags:

views:

38

answers:

1

Is there an way using ADO.NET to determine if a table exists in a database that works with any data provider?

I'm currently doing something like this:

bool DoesTableExist(string tableName)
{
    DbCommand command = this.dbConnection.CreateCommand();
    command.CommandText = "SELECT 1 FROM " + tableName;
    try
    {
        using (DbDataReader reader = command.ExecuteReader())
        {
            return true;
        }
    }
    catch (DbException)
    {
        return false;
    }
}

I'm hoping that there is a way that doesn't involve catching exceptions.

+3  A: 

Well, you can use the Connection.GetSchema("TABLES") method.

This returns a DataTable which will contains rows of all the tables in your DB. From here you can check against this and see if the table exists.

This can then be taken a step further:

    private static bool DoesTableExist(string TableName)
    {
        using (SqlConnection conn = 
                     new SqlConnection("Data Source=DBServer;Initial Catalog=InitialDB;User Id=uname;Password=pword;"))
        {
            conn.Open();

            DataTable dTable = conn.GetSchema("TABLES", 
                           new string[] { null, null, "MyTableName" });

            if (dTable.Rows.Count > 0)
                return true;
            else
                return false;
        }
    }

If you're using .NET 3.5, then you can make this an extension method as well.

Kyle Rozendo
Great. Does the job nicely, thanks.
Ergwun