2010-04-29 53 views
3

我想將數據從一個數據庫的表移動到另一個數據庫的表。我收到一個外鍵錯誤。我怎樣才能插入所有有效的數據,除了那些沒有外鍵的行呢?創建插入查詢(外鍵約束出錯)

我的查詢是:

SET IDENTITY_INSERT City ON 

    INSERT INTO City ([cityid],[city],[country],[state],[cityinfo] 
    ,[enabled],[countryid],[citycode],[stateid],[latitude],[longitude]) 
    SELECT [cityid],[city],[country],[state],[cityinfo] 
    ,[enabled],[countryid],[citycode],[stateid],[latitude],[longitude] 
    FROM TD.DBo.City 

收到此錯誤:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK__city__countryid__3E52440B". The conflict occurred in database "schoolHigher", table "dbo.country", column 'countryId'. 

回答

3

INNER JOIN其他數據庫的表與表country。只有具有現有國家/地區的記錄纔會被選中。

注意:您應該檢查兩個數據庫中相應的countryid是否匹配。

SET IDENTITY_INSERT City ON 

INSERT INTO City (
    [cityid] 
    ,[city] 
    ,[country] 
    ,[state] 
    ,[cityinfo] 
    ,[enabled] 
    ,[countryid] 
    ,[citycode] 
    ,[stateid] 
    ,[latitude] 
    ,[longitude]) 
SELECT ct.[cityid] 
     ,ct.[city] 
     ,ct.[country] 
     ,ct.[state] 
     ,ct.[cityinfo] 
     ,ct.[enabled] 
     ,ct.[countryid] 
     ,ct.[citycode] 
     ,ct.[stateid] 
     ,ct.[latitude] 
     ,ct.[longitude] 
FROM TD.DBo.City ct 
     INNER JOIN dbo.Country cnt ON cnt.CountryID = ct.CountryID 
+0

哇感謝哥們其工作.. – 2010-04-29 11:05:47

+0

別提了,也不要忘了檢查都貴國表。 – 2010-04-29 11:07:34