欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

执行Insert Exec时的隐藏开销 分析

程序员文章站 2022-09-04 08:06:08
the hidden costs of insert exec insert and exec: relational brothers in arms, help...

the hidden costs of insert exec

insert and exec: relational brothers in arms, helping you get your data and then put it somewhere. but like all brothers, their relationship has its ups and downs and sometimes you need to look just below the surface to see the real issues. in this post i will cover hidden penalties that a decision--seemingly purely aesthetic--can bring to the fore.

to illustrate the first of these examples i will be using the following table:

use tempdb
go


create table dbo.mytable
(
    [salesorderid] [int] not null,
    [salesorderdetailid] [int] not null,
    [carriertrackingnumber] [nvarchar](25) null,
    [orderqty] [smallint] not null,
    [productid] [int] not null,
    [specialofferid] [int] not null,
    [unitprice] [money] not null,
    [unitpricediscount] [money] not null,
    [linetotal] [money] not null,
    [rowguid] [uniqueidentifier]  not null,
    [modifieddate] [datetime] not null
)
go

consider the following queries, disregarding the fact that this isn't a good dynamic sql example (i'm trying to keep it simple), and take a moment to think about the differences between them from a behavioral point of view:

exec
('
    insert dbo.mytable
    select *
    from adventureworks.sales.salesorderdetail
')
go

insert dbo.mytable
exec
('
    select *
    from adventureworks.sales.salesorderdetail
')
go

it's quite common to insert some data into a table from dynamic sql, and for as long as i can remember, i've believed the choice between these two forms of the query to be primarily an issue of style. my preference has been for the latter style, as i feel that it's a bit more readable. it also has the benefit of better supporting ownership chains, but that's something that, in most cases, we don't have to worry about any longer in sql server 2005 or 2008. but let's move beyond style and potential security issues and get to the substance. what actually happens when we run these two queries?

in the first case--insert done inside of the exec--the first step is that the outer statement--the exec itself--is parsed and validated. now we jump down one level of context, into the string that was passed to exec, and that string is parsed and validated. the referenced objects are resolved, and the plan cache is checked. if there is no plan, the query is compiled. and then it's executed. data is streamed from salesorderdetail into mytable and when the query inside of the exec is done control returns to the calling context--exec--and assuming there were no errors, the exec is now completed.

in the second case, something quite a bit different occurs. the insert is parsed and validated, and an insert exec plan is generated. this plan does not involve salesorderdetail, as the query optimizer doesn't know at this point in the process where the data will be inserted from, since that step is dynamic. so the plan references something called the "parameter table" (plan truncated for simplicity):

|--table insert(object:([tempdb].[dbo].[mytable]))
   |--top(rowcount est 0)
        |--parameter table scan

once this plan has been generated, we again jump down one level of context, and the inner string is parsed and validated, the referenced object resolved, the cache checked, and the compiled plan executed. but what is this parameter table thing?

here's where things start really diverging. data is not, at this point, streamed from salesorderdetail directly into mytable. rather, it is streamed from salesorderdetail into the parameter table. and the parameter table, as it turns out, is in actuality a hidden temporary table. and not until all of the data has streamed into that hidden temporary table is control resumed by the exec context, and only then does the data start moving into its final home.

the natural question you might be asking yourself at this point is, just how much overhead does this parameter table introduce into the equation? the answer might just send you racing to check your stored procedures: the additional cost for the parameter table is well over 100% as compared with doing the insert inside of the exec. the fact that all of the data must be spooled to the parameter table before the insert can even begin tells us that this must be true, and it can be verified using a simple check against the sys.dm_exec_requests dmv, as in the following example:

exec
('
    insert dbo.mytable
    select *
    from adventureworks.sales.salesorderdetail
')

select
    r.writes as [insert inside exec writes]
from sys.dm_exec_requests r
where
    r.session_id = @@spid
go

insert dbo.mytable
exec
('
    select *
    from adventureworks.sales.salesorderdetail
')

select
    r.writes as [insert exec writes]
from sys.dm_exec_requests r
where
    r.session_id = @@spid
go

so that's that. we should avoid insert exec and try to do our inserts in the same context in which the select is running--right?

well, yes and no. there is another element at play here which i haven't yet mentioned. what if we were only inserting a few rows, and the table we were inserting into looked something like the following:

create table #mytable
(
    [salesorderid] [int] not null,
    [salesorderdetailid] [int] not null,
    [carriertrackingnumber] [nvarchar](25) null,
    [orderqty] [smallint] not null,
    [productid] [int] not null,
    [specialofferid] [int] not null,
    [unitprice] [money] not null,
    [unitpricediscount] [money] not null,
    [linetotal] [money] not null,
    [rowguid] [uniqueidentifier]  not null,
    [modifieddate] [datetime] not null
)
go

the only difference between this table and the previous one is that this is a temporary table and the other is not. but temporary tables have their own interesting little twists, especially when it comes down to one of the key enemies in a highly-transactional system: recompilation. as it turns out, doing the insert inside the exec will cause the internal statement to recompile every time a new temp table is encountered. this means that if you have a stored procedure that creates a temp table, puts together a bit of dynamic sql, and does an insert inside of that dynamic sql, you'll now have yourself a recompilation problem.

to see this illustrated, try the following script. here only a single row is inserted as a result of the dynamic query, but it's complex enough that the compile time more than overshadows the overhead of the parameter table:

use tempdb
go

dbcc freeproccache
go

create table #avgtimes
(
    cpu_time decimal(19,4) not null,
    insert_type varchar(25) not null
)
go

create table #mytable
(
    [salesorderid] [int] not null,
    [salesorderdetailid] [int] not null,
    [carriertrackingnumber] [nvarchar](25) null,
    [orderqty] [smallint] not null,
    [productid] [int] not null,
    [specialofferid] [int] not null,
    [unitprice] [money] not null,
    [unitpricediscount] [money] not null,
    [linetotal] [money] not null,
    [rowguid] [uniqueidentifier]  not null,
    [modifieddate] [datetime] not null
)

exec
('
    insert #mytable
    select top(1)
        sod.*
    from adventureworks.sales.salesorderdetail sod
    where
        sod.unitprice > 10
        and sod.linetotal > 100
        and exists
        (
            select *
            from adventureworks.sales.salesorderheader soh
            join adventureworks.person.contact c on
                c.contactid = soh.customerid
            where
                soh.salesorderid = sod.salesorderid
                and c.lastname like ''ab%''
        )
        and exists
        (
            select *
            from adventureworks.production.product p
            where
                p.productid = sod.productid
                and p.color is null
        )
        and not exists
        (
            select *
            from adventureworks.sales.salesorderheader soh
            join adventureworks.sales.salesperson sp on
                soh.salespersonid = sp.salespersonid
            where
                soh.salesorderid = sod.salesorderid
                and sp.commissionpct > 50
        )
')

insert #avgtimes
select
    r.cpu_time,
    'insert inside exec'
from sys.dm_exec_requests r
where
    r.session_id = @@spid

drop table #mytable
go 5

create table #mytable
(
    [salesorderid] [int] not null,
    [salesorderdetailid] [int] not null,
    [carriertrackingnumber] [nvarchar](25) null,
    [orderqty] [smallint] not null,
    [productid] [int] not null,
    [specialofferid] [int] not null,
    [unitprice] [money] not null,
    [unitpricediscount] [money] not null,
    [linetotal] [money] not null,
    [rowguid] [uniqueidentifier]  not null,
    [modifieddate] [datetime] not null
)

insert #mytable
exec
('
    select top(1)
        sod.*
    from adventureworks.sales.salesorderdetail sod
    where
        sod.unitprice > 10
        and sod.linetotal > 100
        and exists
        (
            select *
            from adventureworks.sales.salesorderheader soh
            join adventureworks.person.contact c on
                c.contactid = soh.customerid
            where
                soh.salesorderid = sod.salesorderid
                and c.lastname like ''ab%''
        )
        and exists
        (
            select *
            from adventureworks.production.product p
            where
                p.productid = sod.productid
                and p.color is null
        )
        and not exists
        (
            select *
            from adventureworks.sales.salesorderheader soh
            join adventureworks.sales.salesperson sp on
                soh.salespersonid = sp.salespersonid
            where
                soh.salesorderid = sod.salesorderid
                and sp.commissionpct > 50
        )
')

insert #avgtimes
select
    r.cpu_time,
    'insert exec'
from sys.dm_exec_requests r
where
    r.session_id = @@spid

drop table #mytable
go 5

select
    avg
    (
        case a.insert_type
            when 'insert inside exec' then a.cpu_time
            else null
        end
    ) as [cpu time - insert inside exec],
    avg
    (
        case a.insert_type
            when 'insert exec' then a.cpu_time
            else null
        end
    ) as [cpu time - insert exec]
from #avgtimes a
go

drop table #avgtimes
go

so what have we learned today? the choice between insert exec and insert inside of exec is not purely stylistic and has definite performance implications. here are the rules i'll be following from now on:

  • when working with permanent tables, always avoid insert exec if possible. there are some cases where it won't be possible to avoid. i only showed dynamic sql in this post, but insert exec also applies to stored procedures. can you safely rip apart all of the stored procedures in your system in order to avoid this issue? maybe not quite as easily as you can rip apart the dynamic sql within stored procedures.
  • when working with temporary tables, evaluate the complexity of the operations, the amount of data to be inserted, and most importantly, test every solution! the more rows that are inserted as a result of the insert exec, the more the overhead you'll get from the parameter table. on the flip side, the more complex the dynamic statement, the more overhead you'll get from recompilations. every scenario is bound to be different and you may just learn something about your processes by doing this extra bit of analysis.