如何从SqlDataReader同时读取两行值

时间:2014-03-11 16:40:09

标签: c# sql-server sqldatareader

如何同时从SqlDataReader的两个连续行读取值?!

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;
                //}
            }

1 个答案:

答案 0 :(得分:1)

你不能直接这样做。每次调用SqlDataReader.Read都会使读者前进,从而可以检索它所指向的行的值。因此,您不能“同时读取两行”。请参阅MSDN Documentation

但是,你可以做的是使用一些临时值:

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));            
        }

未经过测试(也许是错误的,因为我不知道你的方法定义),但我认为你会得到一般的想法。