What would be the best for SQL-Server 2012.
If we have a collection that needs to be inserted to the db. One way is to execute each insert with a parameterized query like this (pseudo)
foreach(car in cars)
(
sqlstring = "INSERT INTO car(name, type) VALUES(@name, @type)
execute
)
Another approach is to each the insert statements together and only execute ones.
foreach(car in cars)
(
sqlstring += "INSERT INTO car(name, type) VALUES(@name+index, @type+index)
)
execute
The second approach will get a lot of cached plans that will probably only be used once. The first approach I think is faster.
There is a third option I know of to use TableValued parameters but let's skip this for this discussion.
What would be the best approach regarding performance?
For a couple of thousand rows, creating an enormous statement to hold everything isn't practical -- parsing the statement and generating a plan will become a noticeable overhead, especially if the query size itself becomes variable. Use single
INSERT
statements instead, but wrap them in a transaction to minimize the overhead of logging.Although you've discarded table-valued parameters, those would also be a viable solution (certainly almost always preferable to huge parameter lists, though there are specialized cases where those work better).