Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do I obtain the row count after I execute the statement
SQLExecDirect(hstmt, "Select Count(*) as Fred from Table", SQL_NTS);
I need to know the number of rows in a table prior to getting the data but I am not sure how the access the result. I am a little confused because the query results in a single value not a result set (e.g. table row).

Does the result set represent a table row with the row count in a column called Fred? If I leave the "as Fred" out does SQL return the result in column 0 of the result set?
Posted
Comments
Sergey Alexandrovich Kryukov 10-Mar-12 21:37pm    
It depends on what do you call "getting the data" in "prior to getting the data".
--SA

1 solution

Please see my question in a comment to the question. Apparently, if you don't get data at all, you have no data, so the question does not make complete sense.

You have a command, now you can create either System.Data.SqlClient.SqlDataReader or System.Data.SqlClient.SqlDataAdapter out of it. If you use a data adapter, you still need to fill the data in the data set or data table. If you have data reader, you only can check up it it has rows (the method HasRows), but you still need to read the data to see how many of them do you have. Perhaps this method would be the closest to the vague idea of "prior to getting the data":

C#
SqlConnection = //...

//...

string queryString = "Select Count(*) as Fred from Table";

SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();

SqlDataReader reader = command.ExecuteReader();
int rowCount = 0;
if (reader.HasRows)
    while (reader.Read()) ++rowCount;
reader.Close();


Please see:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx[^],
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900