C# 'select count' sql command incorrectly

2020-07-11 04:58发布

I'm trying to return the rowcount from a SQL Server table. Multiple sources on the 'net show the below as being a workable method, but it continues to return '0 rows'. When I use that query in management studio, it works fine and returns the rowcount correctly. I've tried it just with the simple table name as well as the fully qualified one that management studio tends to like.

            using (SqlConnection cn = new SqlConnection())
            {
                cn.ConnectionString = sqlConnectionString;
                cn.Open();

                SqlCommand commandRowCount = new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn);
                countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
                Console.WriteLine("Starting row count: " + countStart.ToString());
            }

Any suggestions on what could be causing it?

3条回答
smile是对你的礼貌
2楼-- · 2020-07-11 05:49

Here's how I'd write it:

using (SqlConnection cn = new SqlConnection(sqlConnectionString))
{
    cn.Open();

    using (SqlCommand commandRowCount
        = new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn))
    {
        commandRowCount.CommandType = CommandType.Text;
        var countStart = (Int32)commandRowCount.ExecuteScalar();
        Console.WriteLine("Starting row count: " + countStart.ToString());
    }
}
查看更多
贪生不怕死
3楼-- · 2020-07-11 05:50

You can use this better query:

SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID)=N'YOUR_TABLE_NAME'
查看更多
\"骚年 ilove
4楼-- · 2020-07-11 05:57

Set your CommandType to Text

command.CommandType = CommandType.Text

More Details from Damien_The_Unbeliever comment, regarding whether or not .NET defaults SqlCommandTypes to type Text.

If you pull apart the getter for CommandType on SqlCommand, you'll find that there's weird special casing going on, whereby if the value is currently 0, it lies and says that it's Text/1 instead (similarly, from a component/design perspective, the default value is listed as 1). But the actual internal value is left as 0.

查看更多
登录 后发表回答