Using SqlBulkCopy for inserting to SQL

sqlbulkcopy sql-server


I don't know why data isn't getting into SQL. Can someone please review this and see what's wrong with my code? I got most of the code below from and MSDN page:

Dim connectionString As String = "Server= "<servername>"; integrated security=true"

    Using sourceConnection As SqlConnection = _

        New SqlConnection(connectionString)

        Dim commandSourceData As SqlCommand = New SqlCommand(<TSQL>), sourceConnection)
        Dim reader As SqlDataReader = commandSourceData.ExecuteReader

        Using destinationConnection As SqlConnection = _
            New SqlConnection(connectionString)

            Using bulkcopy As SqlBulkCopy = _
                New SqlBulkCopy(destinationConnection)
                bulkcopy.DestinationTableName = _

                Catch ex As Exception
                End Try

            End Using
        End Using
    End Using

Accepted Answer

In the system where I do a BulkCopy, I set up the column mappings as explained in the documentation Column Mapping - SQL Bulk Copy

The mapping is set up with the source and destination column names. This example is from the documentation:

 Dim mapID As New _
              SqlBulkCopyColumnMapping("ProductID", "ProdID")

When I first set this up, I remember having trouble without explicitly setting up the column mappings in my environment.

Popular Answer

If the field-types, field-orders, fields count of your datasource, are not the same with the destination table. Your bulkcopy will return fail.

In above case, you should specificate the ColumnMappings of each fields in your datasoruce to your sqlbulkcopy object.

            SqlBulkCopy copy = new SqlBulkCopy(MySqlConn);
            copy.BulkCopyTimeout = 6000;
            copy.DestinationTableName = TableName;
            for (int i = 0; i < this.lstBulkFields.Count; i++) {
                // if the source fields name are the same with the targets.
                copy.ColumnMappings.Add(this.lstBulkFields[i], this.lstBulkFields[i]);
            copy.BatchSize = BatchSize;

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why