在临时表上添加聚簇索引以提高性能

时间:2017-06-14 12:15:57

标签: sql-server

我已经运行了一个执行计划,并注意到在插入临时表时查询需要时间。我们有多个插入临时表的查询。我在下面分享了其中两个。如何通过storedprocedure查询将聚簇索引添加到临时表。它需要动态创建索引并销毁它

    if object_id('tempdb..#MarketTbl') is not null drop table #MarketTbl  else

        select 
            mc.companyId,
            mc.pricingDate,
            mc.tev,
            mc.sharesOutstanding,
            mc.marketCap 
        into #MarketTbl
        from ciqMarketCap mc
        where mc.pricingDate > @date
        and mc.companyId in (select val from @companyId)
        ---- pricing table: holds pricing data for the stock pprice

if object_id('tempdb..#PricingTbl') is not null drop table #PricingTbl else
        select
            s.companyId,
            peq.pricingDate,
            ti.currencyId, 
            peq.priceMid
        into #PricingTbl
        from ciqsecurity s
            join ciqtradingitem ti on s.securityid = ti.securityid
            join ciqpriceequity peq on peq.tradingitemid = ti.tradingitemid
        where s.primaryFlag = 1
            and s.companyId in (select val from @companyId)
            and peq.pricingDate> @date
            and ti.primaryflag = 1

执行计划 enter image description here

2 个答案:

答案 0 :(得分:0)

你在做什么是纯粹的废话。你必须加快你的选择,而不是插入。 为了加快速度,您(可能)需要在您选择的表格上使用索引。

你现在正在做的是尝试将聚集索引添加到不存在的表中(错误告诉你它!),并且该表不存在,因为如果存在则删除它

答案 1 :(得分:0)

1.首先,你的数据不超过5到10万,不要使用临时表,使用表类型变量。 2.您可以在插入数据后创建索引,使用alter table语法。