0

我有一个查询需要大约 14 分钟才能使用从链接服务器上的视图中选择的内联表值函数完成。但是,如果将此查询更改为删除该函数并直接从查询中选择,它将在大约 20 秒内完成。

功能:

CREATE FUNCTION [dbo].[fn_GetView](CompanyCharacters VARCHAR(4))
RETURNS TABLE
AS
RETURN
(
    SELECT DISTINCT
           [Some Rows]
    FROM   LinkedServer.Database.dbo.LinkedView
    WHERE  Co_char = RIGHT(REPLACE('0', 4) + 
                           CAST(@CompanyCharacters AS VARCHAR(4)), 4)
)

需要 14 分钟的查询:

SELECT DISTINCT
       [Some Rows]
FROM   fn_GetSomeCompanyData() AS Comp
       JOIN CustomerData ON Comp.ID = CustomerData.CompID
       JOIN fn_GetView('MSF') AS gv ON gv.CompanyChar = Comp.CompanyChar
                                    AND gv.FirstName = Comp.FirstName
                                    AND gv.FirstName = Comp.FirstName

更改的查询需要 20 秒:

SELECT DISTINCT
       [Some Rows]
FROM   fn_GetSomeCompanyData() AS Comp
       JOIN CustomerData ON Comp.ID = CustomerData.CompID
       JOIN LinkedServer.Database.dbo.LinkedView AS gv ON gv.CompanyChar = Comp.CompanyChar
           AND gv.FirstName = Comp.FirstName
           AND gv.FirstName = Comp.FirstName
           AND gv.Co_char = RIGHT(REPLACE('0', 4) + 'MSF', 4)
WHERE [Some Data Filtering]

有人知道为什么会这样吗?是否有最好的方法来更改查询,使其快速但仍能保留该功能?

4

0 回答 0