简体   繁体   中英

Datatable bulk copy to SQL Server merge row id

I am using the code below for insert data from a datatable into SQL Server. My question is if there is any way to merge rows. If id not exist insert, else update.

using (SqlTransaction transaction = connection.BeginTransaction())
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction))
{
    try
    {
        bulkCopy.DestinationTableName = TableName;
        bulkCopy.WriteToServer(dt);
        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        return false;
    }
}

I strongly suggest you use EFC for such things, its easy to handle bulk operations with pseudo objects. You can read about entity framework core bulk operations here: https://dotnetdetail.net/entity-framework-core-3-0-bulk-insert-update-and-delete/

A table-valued parameter with your DataTable value can be used in a MERGE statement for conditional INSERT or UPDATE . Create a table type that matches your DataTable schema, eg:

CREATE TYPE TvpType AS TABLE(
      ID int NOT NULL PRIMARY KEY
    , DataValue int
);

Then pass the DataTable as a parameter of type SqlDbType.Structured to the MERGE statement:

string mergeStatement = @"
MERGE dbo.YourTable AS target
USING @TVP AS source ON source.ID = target.ID
WHEN MATCHED THEN UPDATE SET DataValue = source.DataValue
WHEN NOT MATCHED BY TARGET THEN INSERT (ID, DataValue) VALUES(source.ID, source.DataValue);";

try
{
    using (SqlCommand mergeCommand = new SqlCommand(mergeStatement, connection))
    {
        mergeCommand.Parameters.Add("@TVP", SqlDbType.Structured).Value = dt;
        mergeCommand.ExecuteNonQuery();
    }
}
catch
{
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM