I am trying to refresh a development server with data from production server but this cannot be done by a straightforward restore as the dev environment contains objects not in prod environment that we need to keep. So what I am trying to do is truncate the tables that need refreshing and then insert the data. I have created a procedure just for that and it works till we get to foreign keys.
The DB I inherited is not very well written and has several primary key columns in most tables. I was looking at this question Cannot truncate table because it is being referenced by a FOREIGN KEY constraint? and have incorporated the best solution provided by @peter-szanto and @marc-2377 into the stored procedure that works GREAT as long as there is one unique constraint in the sys.foreign_key_columns inserted into #FKs. Using the script causes error
"There are no primary or candidate keys in the referenced table"
on some tables due them referencing tables with multiple primary key columns as one foreign key.
The code as is returns these to recreate the fks in table FK_stmnt
ALTER TABLE [dbo].[sometable] WITH NOCHECK
ADD CONSTRAINT [sometable$othertable__12345]
FOREIGN KEY([fk1]) REFERENCES [dbo].[othertable] ([pk1])
ALTER TABLE [dbo].[sometable] WITH NOCHECK
ADD CONSTRAINT [sometable$othertable__12345]
FOREIGN KEY([fk2]) REFERENCES [dbo].[othertable] ([pk2])
ALTER TABLE [dbo].[sometable] WITH NOCHECK
ADD CONSTRAINT [sometable$othertable__12345]
FOREIGN KEY([fk3]) REFERENCES [dbo].[othertable] ([pk3])
ALTER TABLE [dbo].[sometable] WITH NOCHECK
ADD CONSTRAINT [sometable$othertable__12345]
FOREIGN KEY([fk4]) REFERENCES [dbo].[othertable] ([pk4])
ALTER TABLE [dbo].[sometable] WITH NOCHECK
ADD CONSTRAINT [sometable$othertable__12345]
FOREIGN KEY([fk5]) REFERENCES [dbo].[othertable] ([pk5])
Need results returned as
ALTER TABLE [dbo].[sometable] WITH NOCHECK
ADD CONSTRAINT [sometable$othertable__12345]
FOREIGN KEY ([fk1], [fk2], [fk3], [fk4], [fk5])
REFERENCES [dbo].[othertable] ([pk1], [pk2], [pk3], [pk4], [pk5])
that is for every sometable$othertable__12345 constraint combine the columns in one statement.
Any ideas please?