gpt4 book ai didi

c# - 如何将值传递给sql server中的 View

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:46 24 4
gpt4 key购买 nike

我创建了一个成功运行的名为 business 的 View ,但问题是我将如何使用动态值代替 12.925432,77.5940171,我想从后面的 c# 代码在 sql 查询中传递参数。

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 ;

这将是我来自后面的 C# 代码的查询。....

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();
.....

最佳答案

我想你需要一个用户定义的函数,所以:

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

然后在代码中你需要这样做:

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

然后您可以将值替换为 selectcommand 的命令文本而不是那些数字。

关于c# - 如何将值传递给sql server中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3614943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com