如何加快mutliple Insert Into / Select From语句的运行时间?

时间:2015-09-18 16:30:35

标签: sql sql-server sql-server-2012 runtime

我要做的第一件事是创建临时表,然后将数据插入到临时表中。每个插入的记录可以是1,500到9,000个记录。

表格创建,以及一条insert into / select语句如下:

create table #temp_table (
    [col1] [datetime] NOT NULL,
    [col2] [nvarchar](35) NOT NULL,
    [col3] [nvarchar](35) NOT NULL,
    [col4] [nvarchar](35) NOT NULL,
    [col5] [varchar](25) NOT NULL,
    [col6] [char](6) NOT NULL,
    [col7] [datetime2](0) NOT NULL,
    [col8] [datetime2](0) NOT NULL,
    [col9] [int] NOT NULL
)

--single insert into/select from statement
insert into #temp_table (
col1
, col2
, col3
, col4
, col5
, col6
, col7
, col8
, col9
) Select pt.col1
, pt.col2
, pt.col3
, pt.col4
, pt.col5
, pt.col6
, pt.col7
, pt.col8
, pt.col9
from dbo.permanent_table as pt
where pt.col6 between getdate()-14 and getdate()-7
and pt.col7 is not NULL
and pt.col6 is not NULL

这完全按预期工作,最多1秒钟,2秒钟。然后我添加第二个,第三个insert into / select from语句(where子句每次更改)并且运行时间增加到总共大约4秒。当我添加第四个insert into / select from时,它会跳跃到3分钟或更长时间。 如何让运行时恢复原状(5秒,可能是6秒)?

注意:当我使用union all方法时,问题仍然存在。

union all方法的示例:

create table #temp_table (
    [col1] [datetime] NOT NULL,
    [col2] [nvarchar](35) NOT NULL,
    [col3] [nvarchar](35) NOT NULL,
    [col4] [nvarchar](35) NOT NULL,
    [col5] [varchar](25) NOT NULL,
    [col6] [char](6) NOT NULL,
    [col7] [datetime2](0) NOT NULL,
    [col8] [datetime2](0) NOT NULL,
    [col9] [int] NOT NULL
)

--union all method of inserting
insert into #temp_table (
col1
, col2
, col3
, col4
, col5
, col6
, col7
, col8
, col9
) 
--select statement 1
Select pt.col1
, pt.col2
, pt.col3
, pt.col4
, pt.col5
, pt.col6
, pt.col7
, pt.col8
, pt.col9
from dbo.permanent_table as pt with (nolock)
where pt.col7 between getdate()-14 and getdate()-7
and pt.col8 is not NULL
and pt.col7 is not NULL
union all
--select statement 2
Select pt.col1
, pt.col2
, pt.col3
, pt.col4
, pt.col5
, pt.col6
, pt.col10 as [col7]
, pt.col11 as [col8]
, pt.col9
from dbo.permanent_table as pt with (nolock)
where pt.col10 between getdate()-14 and getdate()-7
and pt.col11 is not NULL
and pt.col10 is not NULL
--select statement 3
Select pt.col1
, pt.col2
, pt.col3
, pt.col4
, pt.col5
, pt.col6
, pt.col12 as [col7]
, pt.col13 as [col8]
, pt.col9
from dbo.permanent_table as pt with (nolock)
where pt.col12 between getdate()-14 and getdate()-7
and pt.col13 is not NULL
and pt.col12 is not NULL
--select statement 4
Select pt.col1
, pt.col2
, pt.col3
, pt.col4
, pt.col5
, pt.col6
, pt.col14 as [col7]
, pt.col15 as [col8]
, pt.col9
from dbo.permanent_table as pt with (nolock)
where pt.col14 between getdate()-14 and getdate()-7
and pt.col15 is not NULL
and pt.col14 is not NULL

0 个答案:

没有答案