简体   繁体   English

数据表批量复制到 SQL 服务器合并行 id

[英]Datatable bulk copy to SQL Server merge row id

I am using the code below for insert data from a datatable into SQL Server.我正在使用下面的代码将数据表中的数据插入 SQL 服务器。 My question is if there is any way to merge rows.我的问题是是否有任何方法可以合并行。 If id not exist insert, else update.如果 id 不存在插入,否则更新。

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.我强烈建议您将 EFC 用于此类事情,它很容易处理带有伪对象的批量操作。 You can read about entity framework core bulk operations here: https://dotnetdetail.net/entity-framework-core-3-0-bulk-insert-update-and-delete/您可以在此处阅读有关实体框架核心批量操作的信息: 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 .具有 DataTable 值的表值参数可用于条件INSERTUPDATEMERGE语句。 Create a table type that matches your DataTable schema, eg:创建与您的DataTable架构匹配的表类型,例如:

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:然后将DataTable作为SqlDbType.Structured类型的参数传递给MERGE语句:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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