tsql - Batch insert performance

非 Y 不嫁゛ 提交于 2019-12-24 07:03:08

问题


I would like to improve the speed of some inserts on an application I am working on. I had originally created a batch like this:

insert tableA (field1, field2) values (1,'test1'), (2, 'test2')

This works great on SQL Server 2008 and above, but I need my inserts to work on SQL Server 2005. My question is would I get any performance benefit using a batch like this:

insert tableA (field1, field2)
select 1, 'test1'
union all
select 2, 'test2'

Over this batch:

insert tableA (field1, field2) values (1, 'test1')
insert tableA (field1, field2) values (2, 'test2')

回答1:


Altough it may seem that less code to process should give you a performance gain, using first option (union all) is a bad idea. All select statements have to be parsed and executed before the data is inserted into a table. It'll consume a lot of memory and may take forever to finish even for fairly small amount of data. On the other hand separate insert statements are executed "on the fly".

Run a simple test in SSMS that will prove this: create a simple table with 4 fields and try inserting 20k rows. Second solution will execute in seconds, while first... you'll see :).

Another problem is that when the data is not correct in som row (type mismatch for example), you'll receive an error like Conversion failed when converting the varchar value 'x' to data type int., but you'll have no indication which row failed - you'd have to find it yourself. But with separate inserts, you'll know exactly which insert failed.



来源:https://stackoverflow.com/questions/24950629/tsql-batch-insert-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!