Skip some columns in SqlBulkCopy

前端 未结 4 2019
广开言路
广开言路 2021-02-07 15:58

I\'m using SqlBulkCopy against two SQL Server 2008 with different sets of columns (going to move some data from prod server to dev). So wa

4条回答
  •  情深已故
    2021-02-07 16:44

    When SqlBulkCopyColumnMapping is used, only columns for which mappings are created will be copied.

    If you do not create a mapping for a column, it will be ignored by the copy process.

    You can see this in the demo code here - the sample source table in the AdventureWorks demo database contains more columns than are mapped or copied.

    EDIT

    It's difficult to be certain without more information about the database schema, but at a guess the issue is with this statement:

    new SqlBulkCopyColumnMapping(c.ColumnName, c.ColumnName)
    

    From your description, it sounds like not all the columns in the source table exist in the destination table. You need a filter in your SqlBulkCopyColumnMapping construction loop to skip any columns which do not exist in the destination.

    My C# is not good enough to give a example which I'm confident will work, but in pseudocode it would be

    foreach column c in sourcetable
    {
        if c.ColumnName exists in destination_table.columns
        {
              new SqlBulkCopyColumnMapping(c.ColumnName, c.ColumnName)
        }
    }
    

    (I'm sure it's possible to convert this to a lambda expression)

    Note that this is not particularly robust in the scenario where the column names match but the datatypes are incompatible.

提交回复
热议问题