Sql-server – How to troubleshoot “BCP copy in failed”

azure-sql-databasebcpsql server

I have a table that looks something like this in a SQL server database in Azure:

CREATE TABLE [dbo].[TableName](
[col01] [int] IDENTITY(1,1) NOT NULL,
[col02] [varchar](255) NOT NULL,
[col03] [varchar](255) NOT NULL,
[col04] [datetime] NULL,
[col05] [datetime] NULL,
[col06] [nvarchar](255) NULL,
[col07] [nvarchar](max) NULL,
[col08] [nvarchar](255) NULL,
[col09] [nvarchar](max) NULL,
[col10] [int] NULL,
[col11] [nvarchar](255) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

I have a data file that looks a bit like this:

$ head datafile.csv 
2134024,SRC001,SE,NULL,NULL,NULL,NULL,NULL,NULL,1,SRC
2134025,SRC002,SE,NULL,NULL,NULL,NULL,NULL,NULL,2,SRC
2134026,SRC003,SE,NULL,NULL,NULL,NULL,NULL,NULL,3,SRC
2134027,SRC004,SE,NULL,NULL,NULL,NULL,NULL,NULL,4,SRC
2134028,SRC005,SE,NULL,NULL,NULL,NULL,NULL,NULL,5,SRC
2134029,SRC006,SE,NULL,NULL,NULL,NULL,NULL,NULL,6,SRC
2134030,SRC007,SE,NULL,NULL,NULL,NULL,NULL,NULL,7,SRC
2134031,SRC008,SE,NULL,NULL,NULL,NULL,NULL,NULL,8,SRC
2134032,SRC009,SE,NULL,NULL,NULL,NULL,NULL,NULL,9,SRC
2134033,SRC010,SE,NULL,NULL,NULL,NULL,NULL,NULL,10,SRC
$ wc -l 
713224
$ 

I try to import it using bcp running on my linux laptop:

$ bcp TableName in ./datafile.csv -S niceclouddbservername.database.windows.net -U myusername -dmydatabasename -c -t ','
Password: <I paste my password here>


Starting copy... <this takes a few seconds>

BCP copy in failed
$

Two questions, one is interesting right now:

  1. Why doesn't this work?
  2. How can I debug it?

What I have done so far:

  • Used duckduckgo (and google for good measure) to look for an explanation
  • Re-read the docs, found other examples, tried different variations
  • Tried with just the first 10 records
  • Verified (tried to at least) that the datatypes matches the input
  • Testing with a known wrong password to verify that it would produce a different error message
  • Consulted everything that seemed remotely related from the list of "Similar Questions"

Best Answer

Here is how I recommend doing it, which is tailored for character data:

  1. generate format file
  2. edit format file to match the input data structure
  3. upload the data file using the format file generated at step 2

corresponding commands are then as follows:

  1. run bcp [<my_db_name>].<my_schema_name>.<my_table_name> format nul -c -f <my_format_file_name>.fmt -t\<my_delimiter_char> -S <my_db_server> -U <my_db_user>
  2. use any text editor if edition is needed
  3. run bcp [<my_db_name>].<my_schema_name>.<my_table_name> in <my_data_file> -f <my_format_file_name>.fmt -t\<my_delimiter_char> -b <my_batch_size> -m <my_max_errors> -e <my_error_file> -S <my_db_server> -U <my_db_user>

Then, you can inspect <my_error_file> to see how it went. Execution without any error should produce empty <my_error_file>.