0

This answer suggests a handy way to check if a table exists in a database. Is there a somewhat similar kind of way to check if it is not empty perhaps, or should I just query the table a common SQL way find out what's there?

Community
  • 1
  • 1
Ivan
  • 63,011
  • 101
  • 250
  • 382
  • 1
    See if [this](http://stackoverflow.com/questions/5630689/select-all-empty-tables-in-sql-server) helps. Though I would just go with a simple query `SELECT TOP 1 1 FROM Table` – CodingYoshi Apr 24 '17 at 01:19
  • a common SQL way --- you mean not using the master database? how about these [so](http://stackoverflow.com/questions/167576/check-if-table-exists-in-sql-server) – Lei Yang Apr 24 '17 at 01:52
  • @LeiYang "a common SQL way --- you mean..." I mean just writing an SQL query against the table we are interested in and executing it it the ordinary way with a DbCommand rather than trying to find some maintenance/metadata ADO.Net APIs for this. – Ivan Apr 24 '17 at 03:35

1 Answers1

0

Do you know the name of the table? If so, I just use:

using (var dbConnection = new SqlConnection(connectionString))
{
    dbConnection .Open();
    using (var dbCommand = new SqlCommand("select Count(*) from YourTable", dbConnection ))
    {
        return dbCommand.ExecuteScalar() == 0;
    }
}
Dour High Arch
  • 21,513
  • 29
  • 75
  • 90
  • won't throw exception if not exist? – Lei Yang Apr 24 '17 at 01:50
  • The other question already shows how to see if a table exists and this did not answer Ivan's question. If he needs to do that as well, he needs to use the previous answer first. The previous answer does not show if the table is empty. – Dour High Arch Apr 24 '17 at 02:16