简体   繁体   English

如何从SqlDataReader同时读取两行值

[英]How to read two rows values at the same time from a SqlDataReader

How can I read values from two consecutive rows from SqlDataReader at the same time ?! 如何同时从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;
                //}
            }

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. 每次对SqlDataReader.Read调用都会使阅读器前进,从而使您也可以检索它指向的行的值。 Therefore you can't "read two rows at the same time". 因此,您不能“同时读取两行”。 Refer to the MSDN Documentation . 请参阅MSDN文档

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. 没有经过测试(也许是错误的,因为我不知道您的方法定义),但是我认为您将获得大致的了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM