且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

T-SQL CTE实现技术在SQL Server 2012上不起作用

更新时间:2023-02-03 19:26:55

可以尝试使用多步骤表值函数。这样,服务器***将TVF的结果具体化为表格变量。另外,在声明此表类型(PRIMARY KEY,UNIQUE,CHECK)时,您可以尝试使用约束来提高最终查询的性能:

You could try using a multi-step table valued function. This way, the server is forced to materialize the TVF's results into a table variable. Also, you could try using declarative constraints when declaring the this table type (PRIMARY KEY, UNIQUE, CHECK) to improve the performance of the final query:

CREATE FUNCTION CocoJamboSchema.CocoJamboFunction(@parameters ...)
RETURNS @Results TABLE (
    Col1 INT NOT NULL,
    Col2 VARCHAR(10) NULL,
    ...
    PRIMARY KEY(Col1)
)
AS
BEGIN
    WITH MyCTE (...)
    AS
    (
        ...
    )
    INSERT @Results (...)
        FROM MyCTE;

    RETURN;
END;

SELECT ...
FROM CocoJamboSchema.CocoJamboFunction(param values) f
INNER JOIN MySchema.MyTable t ON f.Col1=t.Col1
ORDER BY t.Col1;

别忘了添加 ORDER BY 最后一个查询的子句。

Don't forget to add the ORDER BY clause to your final query.

最近,我使用此解决方案来优化另一个视图(ViewB)使用的视图(ViewA,DISTINCT + LEFT JOIN + GETDATE()) )。在这种情况下(ViewA)无法创建索引视图(因为DISTINCT + LEFT JOIN + GETDATE())。相反,我创建了一个多语句TVF,该功能通过减少最终查询的逻辑读取(在某些情况下过大)来提高性能。

Recently, I used this solution to optimize a view (ViewA, DISTINCT + LEFT JOIN + GETDATE()) used by another views (ViewB). In this case (ViewA) was impossible to create a indexed view (because of DISTINCT + LEFT JOIN + GETDATE()). Instead, I created a multi-statement TVF that improved the performance by reducing the logical reads (drasticaly in some cases) of the final query.

注意:当然,您可以可以尝试使用索引视图

Note: Off course, you could try using an index view.