I am writing a script. The purpose of this script is to

  1. Get all foreign key constraints on a database.
  2. Truncate a table.
  3. Re-Add the foreign key constraints that were removed.

I'm having trouble adding the constraints again [step 3] and I believe this is to do with the fact that my constraint conflicts with what is available. The data initially is...

authors table

1   Kenneth Graham  [email protected]

books table

1   The wind in the willows Classic childrens story about woodland animals  123456

Authorbooks table

1   1   1

I have the following constraints on the authorbooks tables:

ALTER TABLE [dbo].[AuthorBooks]  WITH CHECK ADD  CONSTRAINT [FK_Books_Author_xref_Books] FOREIGN KEY([BookId])
REFERENCES [dbo].[Books] ([ID])
ALTER TABLE [dbo].[AuthorBooks]  WITH CHECK ADD  CONSTRAINT [FK_Books_Author_xref_Authors] FOREIGN KEY([AuthorId])
REFERENCES [dbo].[Authors] ([Id])

So when I try and add the constraints I get the following error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Books_Author_xref_Authors". The conflict occurred in database "PeteDb", table "dbo.Authors", column 'Id'.

Is there any way around this and being able to add the constraint in regardless?

2 Answers 2


Use WITH NOCHECK instead of WITH CHECK to add a constraint that conflicts with existing data. https://stackoverflow.com/questions/529941/whats-the-difference-between-with-check-add-constraint-followed-by-check-constr

Perhaps you are getting the error because you "2. Trucate a table." and not all of them? Maybe you are removing the Authors or the Books and are leaving the records in AuthorBooks that references these other tables.

  • MATE! thanks, saved me a great deal of dissappointment :-) Thougth all my hard work was for nothing....
    – Pete2k
    Nov 3, 2011 at 16:45

Re-Add the foreign key constraints that were removed.

You need not recreate FKs, as the truncate table does not drop them, but only delete the rows.

  • You can't truncate a table that is referenced in a foreign key constraint; therefore you must drop the foreign key constraints first. Hence the need to re-add the foreign key constraints that were removed.
    – user339227
    Nov 8, 2011 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.