问题
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