tags:

views:

36

answers:

2

what is the best way to insert,update batch records from code behind to ms sql?

A: 

Depends on how your data access layer looks like. If you are using enterprise library, then I would say this. And if you are using linq to sql then this.

Ismail
what about linq to sql?
I've updated my answer.
Ismail
it was only a batch update and delete.
A: 

In terms of INSERTs, SqlBulkCopy is the fastest way to bulk load data into SQL Server. I've blogged about how to use it/demonstrated the performance here - comparing to the other approach of using an SqlDataAdapter to send batched inserts via SqlDataAdapter.Update in conjunction with an SqlDataAdapter.InsertCommand.

In terms of UPDATEs, one technique is to bulk load the data into a "temporary" staging table in the database using SqlBulkCopy. And then, run an update on your underlying table from this staging table. Alternatively, you can use the SqlDataAdapter.Update approach, in conjunction with the SqlDataAdapter.UpdateCommand

For raw throughput, SqlBulkCopy (INSERTs only) is the ideal way. However, for handling errors with specific records, the SqlDataAdapter approach is good because you can tell it to continue sending rows to the DB in the event that one fails (e.g. say you get a constraint error on a particular record, you can choose to ContinueUpdateOnError, and then at the end identify those that did error.

AdaTheDev
Hi sir, thank you very much,is the ms sql 2008 capable to accept a parameter of strongly typed list of objects for example List<Person>.Becuase I think 2k8 is capable of passing a parameter type of datatable.
@crisgomez - SQL Server 2k8 does support Table Valued Parameters - so you can pass in a table of data. I did also blog about that technique (comparing it to CSV and XML approaches): http://www.adathedev.co.uk/2010/02/sql-server-2008-table-valued-parameters.html Compared to SqlBulkCopy etc, I don't know what performance is like for real bulk data - would be something to benchmark, it could hit tempdb more
AdaTheDev
what about strongly typed list of object for example List<Person> ,would ms sql 2k8 capable to pass this?
@crisgomez - TBH, I'm not 100% sure. *If* it's possible, you'd have to look into SQL CLR functionality, create a custom SQL CLR type: http://msdn.microsoft.com/en-us/library/ms131120.aspx - not something I've really done much of, so wouldn't want to hazard a guess
AdaTheDev