获取每个批量插入操作中插入的行数

时间:2019-03-12 06:24:40

标签: c# asp.net bulkinsert

我正在使用批量插入操作代码将数据从DataTable插入到SQL表中。如何获得每个批量操作插入的行数?

假设我最初在SQL表中有25行数据,现在在DataTable中有10行数据要通过批量插入操作插入。如何获取插入的行?

var table = "TBL_FINANCE";
using (var conn = new SqlConnection("Server=QD2AOUR;Database=FINANCE; uid=sa; Password=neptune; Initial Catalog=FINANCE;Persist Security Info=True;Trusted_Connection=Yes;Integrated Security=SSPI; pooling=false"))
{
    var bulkCopy = new SqlBulkCopy(conn);
    bulkCopy.DestinationTableName = table;
    conn.Open();
    var schema = conn.GetSchema("Columns", new[] { null, null, table, null });
    foreach (DataColumn sourceColumn in dt.Columns)
    {
        foreach (DataRow row in schema.Rows)
        {
            if (string.Equals(sourceColumn.ColumnName, (string)row["COLUMN_NAME"], StringComparison.OrdinalIgnoreCase))
            {
                bulkCopy.ColumnMappings.Add(sourceColumn.ColumnName, (string)row["COLUMN_NAME"]);
                break;
            }
        }
    }
    try
    {
        bulkCopy.WriteToServer(dt);
    }
    catch (Exception ex)
    {
        lblMessage.Text = "Error with Insert Operation...";
        div_message.Visible = true;
        div_message.Attributes.Add("class", "callout callout-danger");
        return;
    }
    finally
    {
        bulkCopy.Close();
    }
}

0 个答案:

没有答案