为什么在CTE中的WHERE子句之前执行UDF调用?

时间:2018-04-28 17:03:04

标签: sql-server tsql user-defined-functions common-table-expression

我试图理解为什么带有UDF(用户定义函数)调用的CTE(公用表表达式)如此慢。

  • 表TABLE1有1000万行。
  • 最后一个where子句(ROWN = 1)正在过滤并仅返回10条记录。

由于一个不明原因,MYFUNCTION被称为百万次(在WHERE子句过滤器之前)并且它正在减慢查询速度。如果删除了MYFUNCTION调用,则查询会立即运行。

如何在应用WHERE子句后强制SQL运行MYFUNCTION?

WITH MAINDATA
AS
(
    SELECT
        FIELD1,
        FIELD2,
        FIELD3,
        ROW_NUMBER() OVER (PARTITION BY FIELD5 ORDER BY FIELD6) AS ROWN
    FROM
        TABLE1
)
SELECT
    FIELD1,
    dbo.MYFUNCTION(FIELD2, FIELD3) AS FUNCTIONRESULT
FROM
    MAINDATA
WHERE
    ROWN = 1

1 个答案:

答案 0 :(得分:0)

您是否尝试添加顺序cte?

WITH MAINDATA
AS
(
    SELECT
        FIELD1,
        FIELD2,
        FIELD3,
        ROW_NUMBER() OVER (PARTITION BY FIELD5 ORDER BY FIELD6) AS ROWN
    FROM
        TABLE1
) ,
RESULTS (
        SELECT 
            FIELD1
        FROM
            MAINDATA
        WHERE
            ROWN = 1
)
SELECT *
      ,dbo.MYFUNCTION(FIELD2, FIELD3) AS FUNCTIONRESULT
FROM  RESULTS