我想知道是否可以运行SQL查询,该查询返回表中的行数。我有一个页面,点击它,它将运行SQL查询,比较2个表之间的数据,因此我希望用户在一个或多个表为空时得到通知。
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;
}
}
问:我是否使用Select Count(*) from Table
来检索表格中的行数?
如何将Count(*)值存储到整数?
提前谢谢。
我正在使用SQL Server。
答案 0 :(得分:2)
尝试这样的事情:
public int CountRowsInTable()
{
string stmt = "SELECT COUNT(*) FROM dbo.YourTable";
int count = 0;
using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
thisConnection.Close();
}
return count;
}
再说一遍:这样可以准确计算 - 但在大型桌子上它可能非常慢。
备选方案:
SELECT TOP 1....
并确保某些返回) 更新以简单地检查表格是否包含任何行,您可以使用此TOP 1
方法,这应该非常快 - 即使对于大型表:
public bool TableContainsAnyRows()
{
// define a TOP 1 query - typically by the Primary Key of the table in question
// using AdventureWorks sample database here
string stmt = "SELECT TOP 1 [BusinessEntityID] FROM Person.Person ORDER BY [BusinessEntityID]";
bool containsAnyRows = false;
// open a connection and execute this query against the database
using(SqlConnection _con = new SqlConnection("server=.;database=AdventureWorks2008R2;integrated Security=SSPI;"))
using(SqlCommand _cmd = new SqlCommand(stmt, _con))
{
_con.Open();
// getting the result of the query
// if the table contains *any* rows, the result will *NOT* be NULL
object result = _cmd.ExecuteScalar();
_con.Close();
containsAnyRows = (result != null);
}
return containsAnyRows;
}
答案 1 :(得分:0)
SELECT COUNT(*) FROM yourtable;
然后从结果中检索第一行。