需要帮助来优化此查询

时间:2012-10-11 11:20:24

标签: sql-server tsql sql-server-2000

你能帮助我优化我的查询吗?我已经没有办法优化这个。这里的数据检索时间是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

2 个答案:

答案 0 :(得分: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)

在查询结束时。

答案 1 :(得分:0)

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