简体   繁体   English

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

[英]How do I insert records from one table to another when some records don't fit a FK constraint?

I have a source table that has 10,000 records that I want to insert into a destination table. 我有一个源表,其中包含要插入到目标表中的10,000条记录。 The insert would also include an ID field. 插入内容还将包含一个ID字段。 There is a third table with a foreign key relationship on the id field. id字段上还有第三个具有外键关系的表。 How do I insert the records that have the correct ids for the FK and skip the ones that don't have the correct ids for the FK? 如何插入具有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 error I get is 我得到的错误是

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.

You could add an INNER JOIN to the Contacts table to ensure that the [Account Number] from the source matches the Id in the Contacts table. 您可以将INNER JOIN添加到Contacts表中,以确保源中的[Account Number]与Contacts表中的Id匹配。 Anything that doesn't match would get filtered out which should keep you from getting the error about the FK constraint. 任何不匹配的内容都将被过滤掉,这将使您避免收到有关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]

There is probably a query hint or some other database trick that would allow you to pull this off more properly. 可能有一个查询提示或其他数据库技巧可以使您更正确地进行此操作。 But AFAIK the above should work. 但是AFAIK以上应该可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM