我可以在存储过程中动态创建的临时表 (#temp) 上创建索引吗?
我正在存储过程中创建临时表 (#temp_table
)。这是一个包含大量数据的巨大表。然后我在存储过程中创建索引,因为它需要更快地查询临时表。但是当我执行存储过程时,没有使用索引。执行存储过程时未创建索引。
伪代码
CREATE PROC abcdefg
AS
...
SELECT col_a, col_b, col_c....
INTO #temp_table
FROM .....
WHERE ....
...
CREATE INDEX abc_idx ON #temp_table (col_a)
...
SELECT col_a FROM #temp_table WITH (INDEX (abc_idx))
...
GO
当我尝试执行存储过程时,它无法识别索引。我该如何解决这个问题?
I am creating temp tables (#temp_table
) in my stored procedure. It is a huge table with large data. Then I am creating a index in the storeed procedure as it is required for faster query to the temp table. But when I execute the stored procedure, the index is not used. The index is not being created when the stored procedure is executed.
Pseudo code
CREATE PROC abcdefg
AS
...
SELECT col_a, col_b, col_c....
INTO #temp_table
FROM .....
WHERE ....
...
CREATE INDEX abc_idx ON #temp_table (col_a)
...
SELECT col_a FROM #temp_table WITH (INDEX (abc_idx))
...
GO
When I try to execute the stored proc, it is not recognizing the index. How can I fix this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常会发生这种情况,因为临时表的访问计划是在索引存在之前生成的。
幸运的是,您可以使用表级约束来解决这个问题。由于支持 UNIQUE 和 PRIMARY KEY 约束的索引与临时表同时定义,因此优化器将始终能够使用这些索引。
参考:优化临时表的性能/索引
This usually happens because the access plans for the temp tables have been generated before the indexes ever existed.
Fortunately, you can use table-level constraints to get around this problem. Since the indexes to support UNIQUE and PRIMARY KEY constraints are defined at the same time as the temp table, the optimizer will always be able to use these indexes.
Reference: Optimizing Performance / Indexes on Temp Tables
我使用 Sql Server 2005 尝试了您建议的代码,
当运行
包含实际执行计划的命令时,它确实显示索引已被使用。
I tried the code you suggested using Sql Server 2005
When running the
Command with Include Actual Execution Plan, it does show that the index was used.