首页 > 解决方案 > 如何提高将数据插入到组合它的多个表中的查询性能

问题描述

所以在我的第一个表中,我只检索 ID。然后创建和填充多个表变量并通过以下方式对其进行过滤:

where exists(select * from @ID d where d.ID = @TableData.ID) 

所以结构看起来像这样:

    --------------------------------------------
    declare @DateFrom datetime
            @DateTo datetime 
        --table that contain IDs only
              declare @ID table (ID int) 
              insert into @ID 
                select ID 
                from Table
                where dates between @DateFrom and @DateTo 

        --table with data
        declare @TableData
              select 
                case...
                case...
                case...
                case...
            from Table1
                    join Table1
                    join Table1
                    join Table1
            where exists(select * from @ID d where d.ID = @TableData.ID) --filtering only match IDs from @ID table

------------------------------------------------------------------

有什么方法可以以某种方式提高性能吗?

我尝试创建#TempTable,但仍然没有改进。

我想也许有一种方法可以在表变量或临时表上创建索引?

标签: sqlsql-serverperformancesql-server-2012database-administration

解决方案


您可以使用主键创建表变量,但不能使用非聚集索引。

如果你需要在临时表上使用索引,你应该使用#tempTables。然后,您可以在这些上创建索引。在处理大型数据集时,# 的性能优于 @。


推荐阅读