Sql-server – How to add a constraint after I’ve truncated a table

sql server

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  k.graham@twitw.com

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])
GO
ALTER TABLE [dbo].[AuthorBooks]  WITH CHECK ADD  CONSTRAINT [FK_Books_Author_xref_Authors] FOREIGN KEY([AuthorId])
REFERENCES [dbo].[Authors] ([Id])
GO

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?

Best Answer

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.