简体   繁体   中英

Select prepared-statement row count

I may be late to the game here but I am forcing myself into prepared statments for reasons everybody is aware of by now for future development. Thankfully it's been smooth sailing so far! However, i am having a hard time with the following. Below is my VB.NET code snippet:

Dim strConnect As String = "server!"  
Dim cmd As New SqlCommand
Dim cn as SqlConnection = New SqlConnection(strConnect)

Dim str As String = ""
Dim row As SqlDataReader 
cmd = New SqlCommand("SELECT top 10 TypeOfDeliciousPie FROM FamilyLuncheon WHERE MomsSecretSauce  like '%' + @sstring + '%'", cn)
cmd.Parameters.Add("@sstring", SqlDbType.NVarChar).Value = sstring
cn.Open()
row = cmd.ExecuteReader()

While row.Read()
    str += """" + row(TypeOfDeliciousPie ) + ""","
End While
cn.close()

Now, the problem I am having is I need a count of total rows prior to looping though the dataset. In short, I'm building a simple json string manually with the returned data and for the jquery to work properly, I need a total row count.

How best should I go about getting a total row count from a SELECT prepared statement? Before I could simply load it into a datatable and simply table.Rows.count but I can't seem to find something similar. My apologizes if this has previously been covered. I've searched here and google for a proper solution for the past couple hours.

Your help is much appreciated!

You can still use a DataTable when using a SqlCommand for the query, either using a SqlDataAdapter , or using DataTable.Load , eg

Dim dt As DataTable = New DataTable()
dt.Load(cmd.ExecuteReader())

And then use dt.Rows.Count like you are used to.

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