优化距离函数查询 - SQL Server 2005

时间:2013-06-27 00:28:17

标签: sql-server tsql function

我写了一个函数来计算给定最大半径的2个点之间的距离。该函数有效但需要调用两次,我实现它的方式:

进入选择区块,然后再进入where区块。

有没有更好的方法来实现这一目标?

感谢您的帮助!

select
    c.LABEL_NAME,
    k.*,
    dbo.kiw_GetNearMeetingLocationInMiles_FUNC(41.056466,-85.3312009,LATITUDE,LONGITUDE) as distance
    from USR_KIW_CUS_MEETING as k
    join CUSTOMER as c
    on c.MASTER_CUSTOMER_ID = k.MASTER_CUSTOMER_ID
    where c.USR_MEMBERSHIP_STATUS_CODE NOT IN('CR','CSD')
    and dbo.kiw_GetNearMeetingLocationInMiles_FUNC(41.056466,-85.3312009,LATITUDE,LONGITUDE)  <= 120;

更新

这是基于Mathieu Rodic的建议

SELECT
    *
FROM
(
    SELECT
        c.LABEL_NAME,
        k.*,
        dbo.kiw_GetNearMeetingLocationInMiles_FUNC(41.056466,-85.3312009,LATITUDE,LONGITUDE) as distance
    FROM
        USR_KIW_CUS_MEETING as k
    JOIN
        CUSTOMER as c on c.MASTER_CUSTOMER_ID = k.MASTER_CUSTOMER_ID
    WHERE
        c.USR_MEMBERSHIP_STATUS_CODE NOT IN('CR','CSD')
)a
WHERE
   a.distance <= 120

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

SELECT
    *
FROM
(
    SELECT
        c.LABEL_NAME,
        k.*,
        dbo.kiw_GetNearMeetingLocationInMiles_FUNC(41.056466,-85.3312009,LATITUDE,LONGITUDE) as distance
    FROM
        USR_KIW_CUS_MEETING as k
    JOIN
        CUSTOMER as c on c.MASTER_CUSTOMER_ID = k.MASTER_CUSTOMER_ID
    WHERE
        c.USR_MEMBERSHIP_STATUS_CODE NOT IN('CR','CSD')
) AS computed_table
WHERE
    distance <= 120

HAVING子句允许按计算列进行过滤。