当某些记录不符合FK约束时,如何将记录从一个表插入另一个表?

时间:2014-06-05 04:15:20

标签: sql sql-server

我有一个源表,其中有10,000条记录要插入到目标表中。插入还包括ID字段。在id字段上有第三个表具有外键关系。如何插入具有FK正确ID的记录,并跳过那些没有FK正确ID的记录?

Set IDENTITY_INSERT Destination ON
GO

INSERT INTO [dbo].[Destination]
           (
           Id,
           [Street1]
           ,[Street2]
           ,[City]
           ,[State]
           ,[PostalCode]
           ,[ContactId]
           ,[Institution_ID]
           ,[LegacyIDNumber]
           )
 SELECT DISTINCT
 [Account Number],
    [Address],
    [Address 2],
    [City],
    Left([State],2),
    [Postal Code],
    [Account Number],
    [Account Number],
    [Account Number]
FROM  [dbo].[Source]
GO

Set IDENTITY_INSERT Destination OFF
GO

我得到的错误是

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Destination_dbo.Contacts_ContactId". The conflict occurred in database "xxxx", table "dbo.Contacts", column 'Id'.
The statement has been terminated.

1 个答案:

答案 0 :(得分:2)

您可以在“联系人”表中添加INNER JOIN,以确保源中的[Account Number]与“联系人”表中的Id匹配。任何不匹配的东西都会被过滤掉,这会让你无法获得有关FK约束的错误。

SELECT [Account Number],
    [Address],
    [Address 2],
    [City],
    Left([State],2),
    [Postal Code],
    [Account Number],
    [Account Number],
    [Account Number]
FROM  [dbo].[Source]
INNER JOIN dbo.Contacts ON Contacts.id=Source.[Account Number]

可能有一个查询提示或其他一些数据库技巧,可以让你更正确地解决这个问题。但是上面的AFAIK应该可行。