0

I'm trying to get rows count of SqlDataReader with SQL COUNT(). Because of some technical reasons I can't use a counter (increasing a variable while going forwarder). It's my SQL Statement:

(SELECT * FROM [Menus] WHERE MenuParent=@ID);
(SELECT COUNT(*) AS rowsCount FROM [Menus] WHERE MenuParent=@ID)

And it's my .net code:
(It's simple, C#ers can understand it also)

While DR.Read
    If Not DR("rowsCount") Is Nothing Then
    temp &= DR("rowsCount")
    End If
    'blah blah
End While

It does not recognize rowsCount.

What's my wrong?

Whole function: (I used my own classes to connect to the DB) http://pastebin.com/YBZCvvBH

6
  • You need to show us the code before this code. The code where you connect and execute the query and return the results into DR. Commented Jan 30, 2013 at 19:12
  • You can use a SqlDataReader for both. Use NextResult to advance to the next result. Commented Jan 30, 2013 at 19:16
  • @RBarryYoung pastebin.com/YBZCvvBH Commented Jan 30, 2013 at 19:16
  • Please share the technical reason you cannot use a counter? Commented Jan 30, 2013 at 19:28
  • @Blam because it's a recursive function and before making decision I have to know row counts. Commented Jan 30, 2013 at 19:30

3 Answers 3

4

well if you realy want the recordcount inside the resultset

can do this, that seems like your query

    select V.rowsCount,* from [Menus]
    cross join (select COUNT(*) as rowsCount from [Menus] WHERE MenuParent=@ID)V
            WHERE MenuParent=@ID

or just do

    select COUNT(*) over () as rowsCount
    ,* from [Menus]
    WHERE MenuParent=@ID
Sign up to request clarification or add additional context in comments.

1 Comment

There's also the (old now) COMPUTE keyword, or @@rowcount
4

Your SQL statement is returning two result sets. Assuming the order of the SQL statements in your question is the same as the order you are executing, you need to process the data returned by the first query (processing the various menu options) and then execute:

DR.NextResult()

before trying to read the count.

Comments

0
  • Why &=?
  • You're selecting two recordsets. If you want the count, do that first, and separately.

1 Comment

Why be chattier than necessary?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.