如何在SQL where子句中调用函数/过程?

时间:2014-03-21 09:06:30

标签: c# sql stored-procedures user-defined-functions where-clause

在我的sql查询中尝试调用函数时,我一直被困在最后一点。理想情况下,我想做以下事情:

from c in db.items
where calcDistance(c.Latitude, c.Longitude, Latitude, Longitude) =< radius
select ...

但是,据我所知,我不能在where子句中调用本地c#函数。我做了一些研究,并尝试创建一个存储过程来调用用户定义的函数,该函数执行以下等效操作:

CREATE PROCEDURE dbo.DistanceProc
    @lat1 decimal,
    @long1 decimal,
    @lat2 decimal,
    @long2 decimal
AS
    DECLARE @return FLOAT
    SET @return = dbo.Distance(@lat1, @long1, @lat2, @long2)
SELECT @return

其中dbo.Distance是我的用户定义函数,其逻辑与我原来的c#函数相同。然后我尝试添加一个函数import,但没有标量类型FLOAT,我试图返回一个double。然后尝试使用此代码:

from c in db.items
where radius >=  db.DistanceProc(c.Latitude, c.Longitude, Latitude, Longitude)
select ...

但是,db.DistanceProc()返回System.Data.Entity.Core.Objects.ObjectResult&lt; double?&gt;的类型。而不仅仅是正常的双倍。我尝试向此添加.Cast&lt; double&gt;()。FirstOrDefault(),但它无法转换为商店表达式。

此时,我几乎坚持想法。有没有一种简单的方法来实现这一目标?我只需要在DB的每个项目的where子句中执行这个额外的距离计算逻辑。我还看到只返回IEnumerable中的所有项目,然后在本地之后运行逻辑,但由于数据库相当大,所以返回每个项目是不可行的。

谢谢!

编辑:

我也尝试使用these instructions on msdn调用UDF而不是存储过程,但它仍然不起作用。它编译得很好,但在运行时它会抛出NotSupportedException,并带有以下消息:

LINQ to Entities无法识别方法'System.Nullable`1 [System.Double] Distance(System.Decimal,System.Decimal,System.Decimal,System.Decimal)'方法,而且此方法无法翻译成商店表达。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您需要在where子句中调用sql函数,不能调用存储过程。

from c in db.items
where radius >=  db.Distance(c.Latitude, c.Longitude, Latitude, Longitude) -- CALL function instead of procedure