临时表与临时表变量索引

时间:2017-07-19 15:23:30

标签: sql sql-server

我在存储过程中创建了一个临时表,并将其编入索引,并创建一个临时变量表​​并对其进行索引。我发现临时表更快。请参阅下面的实施。有人可以告诉我,我应用索引的方式是否存在差异

临时表实施

if object_id('tempdb..#maxPeriod') is not null drop table #maxPeriod  else
    select 
            fp.companyId,
            max(fi.periodenddate) as maxPeriod
    into #maxPeriod
    from ciqfinperiod fp inner join ciqcompany ci on fp.companyId = ci.companyId
            join ciqfininstance fi on fi.financialperiodid = fp.financialperiodid
    where fp.periodtypeid = 4
            and fi.periodenddate > @date
            and fi.latestforfinancialperiodflag = 1
            and latestfilingforinstanceflag = 1 

    group by fp.companyId

    CREATE NONCLUSTERED INDEX IDX_companyId2 on #maxPeriod(companyId,maxPeriod)

临时表变量实现

DECLARE @maxPeriod TABLE (companyId INT, maxPeriod smalldatetime,
                          UNIQUE NONCLUSTERED  (companyId, maxPeriod))
    INSERT INTO @maxPeriod  
select 
        fp.companyId,
        max(fi.periodenddate) as maxPeriod

from ciqfinperiod fp inner join ciqcompany ci on fp.companyId = ci.companyId
        join ciqfininstance fi on fi.financialperiodid = fp.financialperiodid
where fp.periodtypeid = 4
        and fi.periodenddate > @date
        and fi.latestforfinancialperiodflag = 1
        and latestfilingforinstanceflag = 1 

group by fp.companyId

1 个答案:

答案 0 :(得分:0)

临时表通常更快,请参阅以下链接以获得清晰的解释:https://www.brentozar.com/archive/2014/06/temp-tables-table-variables-memory-optimized-table-variables/