I want to know if it is possible to run a SQL query which returns the number of rows round in a table. I have a page which upon clicked, it will run sql queries which compares data between 2 tables, thus I will want the user to be notified if one or more table is empty.
SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE");
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
try
{
thisConnection.Open();
//sql statement to check if a table is empty
//stores the count value in a integer X
if( X < 1 )
{
Response.Write("<script>alert('Database X is empty');</script>");
return;
}
}
Qs: Do I use Select Count(*) from Table to retrieve the number of rows in a table?
How do I store the Count (*) value into an Integer?
Thank you in advance.
I am using SQL Server.
Try something like this:
Again: this works and gives you an accurate count – but it can be very very slow on large tables.
Alternatives:
SELECT TOP 1....and making sure you get something back)Update: to simply check whether a table contains any rows at all, you could use this
TOP 1approach which should be really fast – even for large tables: