Skip to content
Advertisement

How to copy data from one table to another when foreign key is only defined in the destination table?

Table_A schema:

Id (PK, int)
Name (nvarchar(40))
UserId (**FK**, int)
Date (datetime)*

Table_B schema:

Id (PK, int)
Name (nvarchar(40))
UserId (int)
Date (datetime)

Column UserId is defined as Foreign Key in Table_A.
I need to copy data from Table_B to Table_A and I used:

SET IDENTITY_INSERT Table_A ON

INSERT INTO Table_A ([Id], [Name], [UserId], [Date])
    SELECT [Id], [Name], [UserId], [Date] 
    FROM Table_B

But I get:

The INSERT statement conflicted with the FOREIGN KEY constraint “FK_UserId”
The conflict occurred in database “Table_A”, table “dbo.Users”, column ‘Id’.

Table Users exists of course.

FYI & BTW
This situation is due to the unfortunate fact that the SO Demo Db has no FK information.
See related question

Advertisement

Answer

Well if you really needed to get those records in you would join to the users table to ensure you had vaild userid’s:

INSERT INTO Table_A ([Id], [Name], [UserId], [Date])
    SELECT EData.[Id], [Name], EData.[UserId], [Date] 
    FROM Table_B EData
INNER JOIN Users FKData on FKData.UserID = EData.UserID
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement