1

你能帮我优化我的这个查询吗?我已经没有办法优化这个了。这里的数据检索时间是 6 分钟,我想减少它。希望您能够帮助我。

-- Main query
DECLARE @ProdClass VARCHAR(10)
,@ModelID VARCHAR(10)
,@ServiceStartDate DATETIME
,@ServiceEndDate DATETIME
,@SvcID VARCHAR(10)
,@StateID VARCHAR(10)
,@AreaID VARCHAR(10)

 SET @ProdClass = 'WPS'
 SET @ModelID = 'BM'
 SET @ServiceStartDate = convert(datetime, '10/1/2007')
 SET @ServiceEndDate = CONVERT(DATETIME, '11/1/2007')
 SET @SvcID = '358'
 SET @StateID = 'JB'
 SET @AreaID = ''

SELECT DISTINCT cus.MCUS_CUSID
    ,cus.MCUS_ENAME
    ,mod.MMOD_ENAME
    ,rou.MROU_SERNO
    ,svc.MSVC_SVCID AS SVC_NAME
    ,ar.MARE_ENAME
    ,dbo.ufn_GetLastXApptDate(rou.MROU_ROUID) AS MROU_APTDT
    ,rou.MROU_LSVDT
    ,(
        CASE MROU_FRSVE
        WHEN 'Y'
            THEN 'FREE'
        WHEN 'N'
            THEN 'NORMAL'
        END
    ) AS SERVICE_DUE_TYPE
FROM dbo.MROU_FIL AS rou
INNER JOIN dbo.MCUS_FIL AS cus ON rou.MROU_CUSID = cus.MCUS_CUSID
INNER JOIN dbo.MMOD_FIL AS mod ON rou.MROU_MODID = mod.MMOD_MODID
INNER JOIN dbo.MSVC_FIL AS svc ON rou.MROU_SVCID = svc.MSVC_SVCID
INNER JOIN dbo.MADR_FIL AS adr ON cus.MCUS_CUSID = adr.MADR_CUSID
INNER JOIN dbo.MSTA_FIL AS st ON adr.MADR_STAID = st.MSTA_STAID
INNER JOIN dbo.MARE_FIL AS ar ON adr.MADR_AREID = ar.MARE_AREID
INNER JOIN dbo.FAPT_FIL AS apt ON rou.MROU_ROUID = apt.FAPT_ROUID
WHERE rou.MROU_STAT = 'ACTIVE'
AND rou.MROU_CUSPF = 'MY'
AND apt.FAPT_APTTY in ('mf','m1','m2','m3','m4','m5','m6', 'mm')
AND ((@ProdClass = '') OR (@ProdClass <> '' AND rou.MROU_CLSID = @ProdClass))
AND ((@ModelID = '') OR (@ModelID <> '' AND rou.MROU_MODID = @ModelID))
AND (
    ((@ServiceStartDate = '') OR (@ServiceStartDate <> '' AND rou.MROU_LSVDT >= @ServiceStartDate))
    AND
    ((@ServiceEndDate = '') OR (@ServiceEndDate <> '' AND rou.MROU_LSVDT <= @ServiceEndDate))
)
AND ((@SvcID = '') OR (@SvcID <> '' AND svc.MSVC_SVCID = @SvcID))
AND ((@StateID = '') OR (@StateID <> '' AND adr.MADR_STAID = @StateID))
AND ((@AreaID = '') OR (@AreaID <> '' AND adr.MADR_AREID = @AreaID))
ORDER BY rou.MROU_LSVDT


-- function -- 
ALTER FUNCTION [dbo].[ufn_GetLastXApptDate] 
(
@rouid numeric(18,0)
)
RETURNS datetime
AS
BEGIN
    DECLARE @ApptDate datetime

    SELECT @ApptDate = MAX(FAPT_APTDT)
    FROM dbo.FAPT_FIL
    WHERE FAPT_ROUID = @rouid
        AND FAPT_STAT= 'X'
        AND FAPT_APTTY in ('mf','m1','m2','m3','m4','m5','m6', 'mm')

    RETURN @ApptDate

END
4

2 回答 2

5

SQL Server 必须为每一行调用标量函数。为了让它自由地将函数的查询作为基于集合的操作执行,请移动函数内联。改变:

,dbo.ufn_GetLastXApptDate(rou.MROU_ROUID) AS MROU_APTDT

至:

,(
 SELECT  MAX(FAPT_APTDT)
 FROM    dbo.FAPT_FIL
 WHERE   FAPT_ROUID = rou.MROU_ROUID
         AND FAPT_STAT= 'X'
         AND FAPT_APTTY in ('mf','m1','m2','m3','m4','m5','m6', 'mm')
 )

您的查询也看起来像一个搜索查询,它可能受益于针对不同参数值的不同版本的执行计划。您可以通过添加以下内容为每次执行强制执行新的查询计划:

option  (recompile)

在查询结束时。

于 2012-10-11T11:44:35.707 回答
0

尝试使用键上的所有列创建索引,按照它们在每个表的查询中出现的顺序执行连接。

于 2012-10-11T12:05:31.247 回答