简体   繁体   中英

C# 'select count' sql command incorrectly returns zero rows from sql server

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?

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());
    }
}

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM