0

I am using this code to select users from table in MySql,after i select i calculate the distance between the users and add only the users that are in 10KM from a gps location.

        string commandLine = "SELECT * FROM Users;";

        using (MySqlConnection connect = new MySqlConnection(connectionStringMySql))
        using (MySqlCommand cmd = new MySqlCommand(commandLine, connect))
        {
            connect.Open();
            using (MySqlDataReader msdr = cmd.ExecuteReader())
            {
                ArrayList array = new ArrayList();

                while (msdr.Read())
                {
                    double lon2 = msdr.GetDouble(19);
                    double lat2 = msdr.GetDouble(20);

                    double k = this.GetDistance(lat, lon, lat2, lon2);
                    //k is the distance
                    if (k <= 10)
                    {
                        //Add item to array
                    }
                }
            }
        }

And i want to know if there is a possible to do this calculate with the Sql command instead in the code, because every time i get all the users from a table.

Edit

This is the GetDistance method:

private double GetDistance(double lat,double lon,double lat2,double lon2)
    {
        double ee = (3.1415926538 * lat / 180);
        double f = (3.1415926538 * lon / 180);
        double g = (3.1415926538 * lat2 / 180);
        double h = (3.1415926538 * lon2 / 180);
        double r = (Math.Cos(ee) * Math.Cos(g) * Math.Cos(f) * Math.Cos(h) + Math.Cos(ee) * Math.Sin(f) * Math.Cos(g) * Math.Sin(h) + Math.Sin(ee) * Math.Sin(g));
        double j = (Math.Acos(r));
        double k = (6371 * j);

        return k;
    }
4

2 回答 2

1

I basically injected the formula right into the SQL statement. Try something like this:

SELECT latitude, longitude, SQRT(
POW(69.1 * (latitude - [startlat]), 2) +
POW(69.1 * ([startlng] - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM Users HAVING distance <= 10 ORDER BY distance;
于 2013-07-03T20:28:35.797 回答
0

是的,几乎总有一种方法可以在 T-SQL 中做类似的事情。T-SQL 支持多种数学运算,因此您可以在选择用户时创建变量、分配变量并在您的 T-SQL 逻辑中使用它们。

请参考http://msdn.microsoft.com/en-us/library/ms177516.aspx了解更多信息。

于 2013-07-03T20:32:04.573 回答