![](/img/trans.png)
[英]Store in a variable the number of rows from a table where a column has a certain value in SQL Server Compact
[英]SQL Store number of rows in a table
我想知道是否可以運行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
來檢索Select Count(*) from Table
中的行數?
如何將Count(*)值存儲到Integer中?
先感謝您。
我正在使用SQL Server。
嘗試這樣的事情:
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;
}
SELECT COUNT(*) FROM yourtable;
然后從結果中檢索第一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.