SQL 服务器 - 有什么方法可以加快插入 TVF 中的 table 变量的速度吗?

SQL Server - Is there any way to speed up inserts into a table variable in a TVF?

我的查询运行时间约为 6 秒。目前,它输出大约 1500 条记录,然后将这些记录插入到 table 变量中。插入 table 需要 7 秒。

如果我用临时 table 尝试同样的事情,插入只需要大约一秒钟。

问题是查询被放置在 TVF 中(并且对该函数有很多依赖性,因此将其转换为存储过程并不是最理想的解决方案)所以我不能使用临时 tables。

有什么方法可以加快插入 table 变量的速度吗?我正在使用 SQL Server 2012,因此内存优化 table 变量也不是一个选项。

非常感谢任何建议,提前致谢!

编辑(附加信息):

我尝试了一种类似于 here 所示的 CTE 方法,开销类似于使用临时 table 方法,现在查询大约需要 8 秒。这些 table 变量中的三个(每个给出的输出略有不同)组合在一起,查询总共需要大约 24 秒,这对于我们使用它的目的来说是完全可以接受的table。

您可以在批量插入之前停止创建索引,并在插入之后重新启用它们

-- Disable Index

ALTER INDEX [IXYourIndex] ON YourTable DISABLE
GO

-- Insert Data

-- Enable Index

ALTER INDEX [IXYourIndex] ON YourTable REBUILD
GO

鉴于存储结果 table 变量的最终目标是执行隔离查询并将它们联合起来提供输出,以下使用 CTE 的方法与查询开销时间相同(甚至更快) ) 作为临时 table:

;WITH CTE1 as
(
    --Query 1 (took 6 seconds)
),
CTE2 as
(
    --Query 2 (took 6 seconds)
),
CTE3 as
(
    --Query 3 (took 8 seconds)
)
SELECT cte1.fielda, cte2.fieldb, cte3.fieldc, ...
FROM cte1
JOIN cte2 on cte1.fieldx = cte2.fieldx
JOIN cte3 on cte1.fieldx = cte3.fieldx

-- Total duration 20 seconds
-- Took 39 seconds previously