创建插入查询(外键约束错误)

时间:2010-04-29 10:50:39

标签: sql sql-server sql-server-2005 insert foreign-keys

我想将数据从一个数据库的表移动到另一个数据库的表。我收到外键错误。如何插入除了那些没有外键的行以外的所有有效数据?

我的查询是:

  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'.

1 个答案:

答案 0 :(得分: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
相关问题