0

How can I read values from two consecutive rows from SqlDataReader at the same time ?!

SqlCommand query2 = new SqlCommand("SELECT lon , lat FROM Student Where B_ID = @B_ID ORDER BY Distance ASC");
// some value for @B_ID
            query2.Connection = cn;
SqlDataReader readStd = query2.ExecuteReader();
while (readStd.Read())
            {
                // here I want to calculate the distance between each consecutive rows 
// by taking the latitude and longitude from each row
                    double d = DistanceBetweenPlaces(Convert.ToDouble(readStd.GetValue(0)), Convert.ToDouble(readStd.GetValue(1)), ???, ???);
                    totalDistance = totalDistance + d;
                //}
            }
2
  • Why don't you simply use a temp variable ? Commented Mar 11, 2014 at 16:42
  • 2
    Why not just read the two rows in succession, storing the values in local variables, and then perform the calculation on that? Commented Mar 11, 2014 at 16:43

1 Answer 1

1

You can't do that directly. Each call to SqlDataReader.Read advances the reader, allowing you to retrieve the values of the row it is pointing too. Therefore you can't "read two rows at the same time". Refer to the MSDN Documentation.

What you can do, however, is using some temporary values like that :

SqlCommand query2 = new SqlCommand("SELECT lon , lat FROM Student Where B_ID = @B_ID ORDER BY Distance ASC");
    // some value for @B_ID
    query2.Connection = cn;
    SqlDataReader readStd = query2.ExecuteReader();
    double tempLong = 0.0;
    double tempLat = 0.0;
    bool isFirstIteration = true;
    while (readStd.Read())
        {
            if(isFirstIteration)
            {
                isFirstIteration = false;
            }
            else
            {
                double d = DistanceBetweenPlaces(tempLong, tempLat, Convert.ToDouble(readStd.GetValue(0)), Convert.ToDouble(readStd.GetValue(1)));
                totalDistance = totalDistance + d;
            }
            tempLong = Convert.ToDouble(readStd.GetValue(0));
            tempLat = Convert.ToDouble(readStd.GetValue(1));            
        }

Not tested (and maybe wrong because I don't know your method definition), but I think you will get the general idea.

Sign up to request clarification or add additional context in comments.

Comments

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.