How to read the LAST record of datareader?

G

Guest

Hi

How to read the LAST record of datareader? Here is my code

[code

StringBuilder objBuilder = new StringBuilder()
objBuilder.Append("SELECT startdate, enddate FROM records where userid = '")
objBuilder.Append(id)
objBuilder.Append("'")

SqlDataReader dr = null
int RecordCount = 0

tr

dr = SqlHelper.ExecuteReader(DBConnection.ConnString, CommandType.Text, objBuilder.ToString())

while (dr.Read()

RecordCount++


if(dr.) // how to read the LAST record of the selected rows

this.StartDate = Convert.ToDateTime(dr["startdate"])
this.EndDate = Convert.ToDateTime(dr["enddate"])



[/code

I know how to count the total number of row. But, I only need the last row of data. dr.Read() gets the first row only. How can I do it

Thanks for hel
 
J

Jon Skeet [C# MVP]

Tom said:
I know how to count the total number of row. But, I only need the
last row of data. dr.Read() gets the first row only. How can I do it?

I would suggest reversing the order of your query (which is currently
unordered as far as I can see - selecting just the last result could
give you a different record each time) and using SELECT TOP 1. Then you
know you'll only get one record.

I'd also highly recommend using a parameter instead of adding a string
directly into the SQL.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top