简体   繁体   中英

InvalidOperationException while trying bulkInsert the datatable into SQL Server

I got data from text file into datatable and now when I am trying to insert that data into a SQL Server 2008 database, I get the following error:

InvalidOperationException: String or binary data would be truncated

I cannot get the source of error ie which record is throwing this error.

The code is as below

for (int i = 0; i < dt.Columns.Count; i++)
{
    if (i == 159)
    {
    }
    bulkCopy.ColumnMappings.Add(dt.Columns[i].ColumnName,DestTable.Columns[i].ColumnName);
}

bulkCopy.BulkCopyTimeout = 600;
bulkCopy.DestinationTableName = "dbo.TxtFileInfo";
bulkCopy.WriteToServer(dt);

I have the datatable in the dt variable. And matched columns for both datatable created from text file and also the empty table created in database to add the values to it.

I have copied all records from text file into datatable using below code.

while (reader.Read())
{
      int count1 = reader.FieldCount;

      for (int i = 0; i < count1; i++)
      {
          string value = reader[i].ToString();                            
          list.Add(value);
      }

      dt.Rows.Add(list.ToArray());
      list.Clear();
}

I have got proper records from the text file. Also the number of columns are equal. My database table TextToTable has all columns of datatype nvarchar(50) and I am fetching each record as string from text file. But during bulk insert the error shown is

Cannot convert string to nvarchar(50)

Seems you are trying to insert data which has less length in DB (for example: you have data length 20 but in DB accept only 10 )

To check data which is coming from text file. Have if condition to check length of data in your code and have break point to troubleshoot.

If yes then increase the length of column in DB.

alter tablename
alter column columnname varchar(xxx)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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