我试图优化这个查询,当在一个过程中运行参数(日期时间或日期)在哪里时,它非常慢。但是,当我在过程外执行查询时,它会快速返回数据。
你能帮我一把吗?
WITH PRINCIPAL AS
(
SELECT
C.Empcod, C.MovEstqChv,
SUM(NF.NFPESOLIQ) AS PESOLIQ
FROM
MOV_ESTQ_DOC_COMPLEM C WITH (NOLOCK)
INNER JOIN
MOV_ESTQ M WITH (NOLOCK) ON C.EmpCod = M.EmpCod
AND C.MovEstqDocComplemChv = M.MOVESTQCHV
INNER JOIN
NOTA_FISCAL NF WITH (NOLOCK) ON NF.EMPCOD = C.EMPCOD
AND NF.CTRLDFMODFORM = C.MovEstqDocComplemEspec
AND NF.CtrlDFSerie = C.MovEstqDocComplemSerie
AND NF.NFNum = MovEstqDocComplemNum
WHERE
CONVERT(DATE, M.MovEstqDataEmissao) >= CONVERT(DATE, DATEADD(MM, DATEDIFF(MM, 0, @dtEmissao) + 0, 0))
AND CONVERT(DATE, M.MovEstqDataEmissao) <= CONVERT(DATE,DATEADD(D, -DAY(@dtEmissao), DATEADD(M, 1, @dtEmissao)))
AND NF.NFNatOpProd = '5.905'
GROUP BY
RIGHT(CONVERT(VARCHAR(8), M.MovEstqDataEmissao, 3),5),
C.MovEstqChv, C.EmpCod
),
SECUNDARIO AS
(
SELECT
C.Empcod, C.MovEstqChv,
CTRC.MovEstqValDoc / SUM(nfpesoliq) VALOR_FRETE_PESO
FROM
MOV_ESTQ_DOC_COMPLEM C WITH(NOLOCK)
INNER JOIN
MOV_ESTQ M WITH(NOLOCK) ON M.EMPCOD = C.EMPCOD
AND M.MOVESTQCHV = MovEstqDocComplemChv
INNER JOIN
MOV_ESTQ M2 WITH(NOLOCK) ON M2.MovEstqDocEmpCod = C.EMPCOD
AND M2.MovEstqDocEspec = MovEstqDocComplemEspec
AND M2.MovEstqDocSerie = MovEstqDocComplemSerie
AND RIGHT(M2.MovEstqDocNum, 6) = RIGHT(MovEstqDocComplemNum, 6)
AND M2.MOVESTQCHV = C.MovEstqDocComplemChv
LEFT JOIN
NOTA_FISCAL N WITH(NOLOCK) ON M2.MovEstqDocEmpCod = N.EMPCOD
AND M2.MovEstqDocEspec = N.CtrlDFModForm
AND M2.MovEstqDocSerie = N.CtrlDFSerie
AND M2.MovEstqDocNum = N.NFNUM
INNER JOIN
MOV_ESTQ CTRC WITH(NOLOCK) ON CTRC.EMPCOD = C.EMPCOD
AND CTRC.MOVESTQCHV = C.MOVESTQCHV
WHERE
N.NFPesoLiq > 0
AND CONVERT(DATE, CTRC.MovEstqDataEmissao) >= CONVERT(DATE, DATEADD(MM, DATEDIFF(MM, 0, @dtEmissao) + 0, 0))
AND CONVERT(DATE, CTRC.MovEstqDataEmissao) <= CONVERT(DATE, DATEADD(D, -DAY(@dtEmissao), DATEADD(M, 1, @dtEmissao)))
GROUP BY
CTRC.MovEstqValDoc, C.MovEstqChv, C.Empcod
)
SELECT
@vlFreteTransferencia = SUM(SECUNDARIO.VALOR_FRETE_PESO * PRINCIPAL.PESOLIQ) / SUM(PRINCIPAL.PESOLIQ)
FROM
PRINCIPAL WITH(NOLOCK)
INNER JOIN
SECUNDARIO WITH(NOLOCK) ON PRINCIPAL.MOVESTQCHV = SECUNDARIO.MovEstqChv
AND PRINCIPAL.EmpCod = SECUNDARIO.EmpCod
荷。