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.
To check if table exists in a database you need to use a Select statement on the information schema TABLES or you can use the metadata function OBJECT_ID(). The INFORMATION_SCHEMA. TABLES returns one row for each table in the current database.
To check if a table exists in SQL Server, you can use the INFORMATION_SCHEMA. TABLES table. You can use this table with an IF THEN clause do determine how your query responds whether or not a table exists.
Establish Connection to DatabaseBrowse your database file and click the OK button. After connecting to the new database file create an object of OleDBConnection class in case of a database like Oracle or MS-Access and create an object of SqlConnection class in case of MS-SQL database.
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" });
return dTable.Rows.Count > 0;
}
}
If you're using .NET 3.5, then you can make this an extension method as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With