Using SQLBulkCopy to Insert/Update database

风格不统一 提交于 2019-11-28 11:12:42

SqlBulkCopy is only used for inserting records, not updating them as explained here. You'd need to use a different technique to do bulk updates.

e.g. you could SqlBulkCopy into a staging table, then run some SQL to update from there to the main table.

Truncate the table and perform Bulkcopy.

Avoid Truncate table and Create a new temporary table, which BTW consume more space and memory.

I created a Trigger with INSTEAD OF INSERT and use inside MERGE statement.

But don't forget add the parameter SqlBulkCopyOptions.FireTriggers in the SqlBulkCopy.

This is my two cents.

Like mentioned by AdaTheDev, SqlBulkCopy can only insert however there is an alternative library which allow to perform Upsert operations.

Disclaimer: I'm the owner of the project Bulk Operations

The Bulk Operations library has a method "BulkMerge" which Insert or Update rows based on the specified key.

var bulk = new BulkOperation(connection);

bulk.ColumnMappings.Add("ID", true);
bulk.ColumnMappings.Add("Column1");
bulk.ColumnMappings.Add("Column2");
bulk.ColumnMappings.Add("Column3");

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