开发者

How to pass values to a view in sql server

I have created a view called business this runs sucessfully ,but the problem is how will i use dynamic values in place of 12.925432,77.5940171 ,I want to pass parameter in sql query from c# code behind.

create view [dbo].[business] as 
SELECT Id,
       Name1,
       ZipCode,
       StreetName,
       StreetNumber,
       State1,
       Lat,
       Lng,
       Keyword, 
       ( 6371 * ACOS( COS( (12.925432/57.2958) ) * COS(  (Lat/57.2958)  ) * COS( ( Lng/57.2958 ) - (77.5940171/57.2958) )  + SIN( 12.925432/57.2958 ) * SIN(  Lat/57.2958  ) ) ) AS distance 
  FROM Business_Details  ;

This will be my query from c# code behind. ....

DataSet ds = new DataSet();

SqlCommand com = new SqlCommand();
SqlDataAdapter sqlda = new SqlDataAdapter(com);
//sqlda.SelectCommand.CommandText = "SELECT Id,Name1,ZipCode,StreetName,StreetNumber,State1,Lat,Lng,Keyword, ( 6371 * ACOS( COS( (12.925432/57.2958) ) * COS(  (Lat/57.2958)  ) * COS( ( Lng/57.2958 ) - (77.5940171/57.2958) ) + SIN( 12.925432/57.2958 ) * SIN(  Lat/57.2958  ) ) ) AS distance FROM Business_Details where( (StreetName like '%jayanagar%')and (Keyword like '%plumbing%' ))ORDER BY distance;";

sqlda.SelectCommand.CommandText = "select * 
                                     from business 
                                    where (( distance < '" + radius + "' )
       开发者_运维百科                               and (StreetName like '%" + streetname + "%')
                                      and (Keyword like '%" + keyword1 + "%' )) 
                                 order by distance";
sqlda.SelectCommand.Connection = con;
sqlda.Fill(ds);
con.Close();
.....


I think you would need a user defined function for that, so:

CREATE FUNCTION spherical_distance(@a float, @b float, @c float)
RETURNS float
AS
BEGIN
    RETURN ( 6371 * ACOS( COS( (@a/@b) ) * COS(  (Lat/@b)  ) * COS( ( Lng/@b ) - (@c/@b) )  + SIN( @a/@b ) * SIN(  Lat/@b  ) ) )    
END

create view [dbo].[business] as 
SELECT Id,
       Name1,
       ZipCode,
       StreetName,
       StreetNumber,
       State1,
       Lat,
       Lng,
       Keyword
  FROM Business_Details

Then in code you would need to do this:

sqlda.SelectCommand.CommandText = "select *, spherical_distance( 12.925432, 57.2958, 77.5940171) as distance
                                     from business 
                                    where (( distance < '" + radius + "' )
                                      and (StreetName like '%" + streetname + "%')
                                      and (Keyword like '%" + keyword1 + "%' )) 
                                 order by spherical_distance(12.925432,57.2958,77.5940171)";

Then you would substitute values into the commandtext of the selectcommand instead of those numbers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜