Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get SqlBulkCopy to tell me which column had the truncation error

Tags:

c#

sql-server

I am using SqlBulkCopy to import from an external DB. When importing into an nvarchar column, if the column isn't big enough to hold the incoming string, it fails with:

InvalidOperationException: The given value of type String from the data source cannot be converted to type nvarchar of the specified target column. String or binary data would be truncated.

I'd sure like to be able to tell the user what target column had the problem. I've combed through the exception, but don't see it anywhere. Is there a way to set things up so the name or index of the column comes back in the exception?

Here is the pseudo code of my bulk copy:

using (DbConnection source = DataTableProviderAssists.GetTypedDbConnection(package.ImportSourceType, package.UnencryptedConnectionString))
{
    using (DbCommand cmd = GetCommand(package, source))
    {
        source.Open();

        reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(RequestContext.ConnectionString, SqlBulkCopyOptions.TableLock))
        {
            bulkCopy.DestinationTableName = temporaryTableName;
            bulkCopy.BatchSize = 40000;
            bulkCopy.BulkCopyTimeout = 60000;

            foreach (ImportField field in package.Fields)
            {
                bulkCopy.ColumnMappings.Add(field.Name, field.Name);
            }

            bulkCopy.WriteToServer(reader);
        }
    }
}

Thanks

like image 338
ryanman Avatar asked Jun 29 '10 23:06

ryanman


1 Answers

I am not sure that there is.
You may need to tackle this one in a different way.
Try using Microsoft.SqlServer.Management.Smo API to query your destination table, and figure out what the maximum length of the columns in your table are.
Once you have those, you can pre-read your source data, and fire exceptions immediately.
Have fun.

like image 76
blorkfish Avatar answered Oct 21 '22 14:10

blorkfish