I'm using SSIS to dump data from my SQL Server 2008 prod database to flat files and then using bulk insert to load those flat files into the SQL Server 2008 dev database. The SSIS package is running a TRUNCATE TABLE statement before the bulk insert, but when I run it I still get this error: "The statement has been terminated. Violation of PRIMARY KEY constraint. Cannot insert duplicate key." Why would there be a duplicate key after a truncate? Is there something more I need to do to clear the primary keys before the bulk insert?
1 Answer
If you've truncated the table, then a primary key violation must be coming from duplicate data in the file. Try bulk inserting into a new table, without the PK constraint, and then check the table for duplicates (probably easier than writing some tool or script to parse the file directly). You can create a mimic table that won't have constraints this way:
SELECT * INTO dbo.new_bulk_source
FROM dbo.old_source
WHERE 1 = 0;
Then change your package to reference this table, do the insert, then run:
SELECT key FROM dbo.new_bulk_source
GROUP BY key
HAVING COUNT(*) > 1;
I bet a donut the call is coming from inside the house (or the truncate is not succeeding).
-
1The truncate was not working. It looks like the foreign keys were getting in the way, so I disabled the constraints in the query and changed the truncate to a delete. I'm puzzled why the failed truncate wouldn't show up as an error, though. Commented Aug 3, 2012 at 18:51
-
@stomcavage sorry, not an SSIS guy at all, but try/catch in the package perhaps? Or some setting to ignore errors? Commented Aug 3, 2012 at 19:00