I’m trying out the BCP utility on SQL Server 2008 Express. I don’t think that what I’m trying to do could be more trivial, but still I’m getting a primary key violation when trying to insert two rows into an empty table.
Here is the table DDL:
CREATE TABLE [dbo].[BOOKS](
[BOOK_ID] [numeric](18, 0) NOT NULL,
[BOOK_DESCRIPTION] [varchar](200) NULL,
CONSTRAINT [BOOKS PK] PRIMARY KEY CLUSTERED
(
[BOOK_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Here is the BCP format file:
10.0
2
1 SQLNUMERIC 0 3 "\t" 1 BOOK_ID ""
2 SQLCHAR 0 0 "\r\n" 2 BOOK_DESCRIPTION Modern_Spanish_CI_AS
and here is my input file:
101 BOOK_ABC_001<CR><LF>
102 BOOK_ABC_002<CR><LF>
finally here is the command I run:
bcp Database.dbo.BOOKS in books.txt -T -f BOOKS-format.fmt
and here is the error I get:
Starting copy...
SQLState = 23000, NativeError = 2627
Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]Violation of PRIMARY KEY constraint 'BOOKS PK'. Cannot insert duplicate key in object 'dbo.BOOKS'.
SQLState = 01000, NativeError = 3621
Warning = [Microsoft][SQL Server Native Client 10.0][SQL Server]The statement has been terminated.
BCP copy in failed
Now, BCP succeeds if I use an input file with a single line. In this case, the BOOK_ID column gets assigned a value of 0. So it seems that the first field in my input file is being ignored, and 0 is being used as the value for BOOK_ID for all the rows, which would explain the PK violation error.
So the question is, what is wrong in my format or input files that causes the first column to be ignored?
Thanks.
I’ve never seen a primary key column with datatype DEC, not sure if decimals work. I’ve always used integer.
BUT what i think the problem is the PK column doesn’t have identity set, so it’s not auto incrementing when it adds a new row. In your table create code, replace:
[BOOK_ID] [numeric](18, 0) NOT NULL,
with
[BOOK_ID] [int] IDENTITY(1,1) NOT NULL,
Cheers