Vuk Vasić
Vuk Vasić

Reputation: 1408

Assign return value of function to column of mssql query

If someone know i would be very thankful to help me how to assign return value of function as a field that can be printed on screen here is my code and a little better explanation:

  SqlCommand myCommand = new SqlCommand("SELECT latitude,longitude,name FROM otherLocations WHERE dbo.DistanceInKm(" +myx + "," + myy + "," + "latitude" + "," + "longitude" + ") < 5", connection);
        SqlDataReader myReader = null;
        myReader = myCommand.ExecuteReader();
        while (myReader.Read())
        {
            Response.Write(myReader["latitude"].ToString() + "<br>");
            Response.Write(myReader["longitude"].ToString() + "<br>");
            Response.Write(myReader["name"].ToString() + "<br>");
        }

I want to assign dbo.DistanceInKm return value to some field so i can show it on page by calling Response.Write(myReader["thatfield"].ToString() + "<br>"); So what i want to do is to add field that is defined with distanceinkm function for each row in table so i can print it on page or sort result by it.

Upvotes: 0

Views: 151

Answers (1)

jrummell
jrummell

Reputation: 43067

Add the function to your select list with an AS clause:

string query = @"SELECT latitude, longitude, name, 
     dbo.DistanceInKm(" +myx + "," + myy + "," + "latitude" + "," + "longitude" + @") < 5 
     as distance";

Then you can get the value from reader like any other column:

string distance = myReader["distance"].ToString();

Upvotes: 1

Related Questions