C# SQL存储表中的行数

C# SQL存储表中的行数,c#,sql-server,C#,Sql Server,我想知道是否可以运行一个SQL查询来返回表中的行数。我有一个页面,点击后,它将运行sql查询,比较两个表之间的数据,因此我希望用户收到通知,如果一个或多个表是空的 SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"); SqlCommand nonqueryCommand = thisConnection.CreateCommand(); try { thi

我想知道是否可以运行一个SQL查询来返回表中的行数。我有一个页面,点击后,它将运行sql查询,比较两个表之间的数据,因此我希望用户收到通知,如果一个或多个表是空的

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;
        }
     }
SqlConnection thisConnection=newsqlconnection(“数据源=DATASOURCE”);
SqlCommand nonqueryCommand=thisConnection.CreateCommand();
尝试
{
thisConnection.Open();
//用于检查表是否为空的sql语句
//将计数值存储在整数X中
if(X<1)
{
Write(“警报('Database X为空');”;
返回;
}
}
Qs:我是否使用表中的
选择计数(*)来检索表中的行数

如何将Count(*)值存储到整数中

先谢谢你


我正在使用SQL Server

SELECT COUNT(*) FROM yourtable;

然后从结果中检索第一行。

尝试以下操作:

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;
}
再次强调:这是有效的,可以给你一个准确的计数——但是在大的表上它可能非常慢

备选方案:

  • 查看系统目录视图以获得近似计数(不准确-但快速)
  • 不计算-但只需确保至少有一行(使用
    选择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;
}

如何将计数值存储为整数?这取决于您的编程语言。我只能看到您没有使用Java,我不喜欢猜测.Works-但在大型表(>1亿行)上,这会非常慢…@marc_s他说他担心表是空的。。。我有点怀疑数百万行是否会成为一个问题:)与其检查计数,不如使用
TOP 1
检查表中是否至少有一行。不是吗?TOP1非常特定于服务器。这在Oracle、DB2和MySql上是行不通的。OP还没有提到他的db供应商。嗨,shahkalpesh,我想该声明将从表中选择Top1*。但之后如何检查它是否为空?Count(*)返回一个整数,而不是一整行数据。我想要所有其他数据做什么?如何使用
TOP 1
将查询存储到变量中,并检查它是否为空?@RUiHAO:用
TOP 1
查询的示例更新了我的回答