【问题标题】:MSSQL: Unable to create relationships for two foreign keys to the same table?MSSQL:无法为同一张表的两个外键创建关系?
【发布时间】:2011-08-05 11:47:57
【问题描述】:

您好,使用 SQL Server 2008,

我为棒球联盟建立了一个小型数据库,在创建 Teams(PK: TeamID) 和 GameSchedule(PK: GameID, FK1: HomeTeamID, FK2: AwayTeamID) 之间的关系时遇到问题

我想在 GameSchedule HomeTeamID、AwayTeamID 和 Teams(TeamID) 之间建立关系

每当我尝试这样做时,我都会收到错误消息:(TeamID 已经是 Teams 中的主键)

“团队”表已成功保存 “游戏时间表”表 - 无法创建关系“FK_GameSchedule_Teams”。
ALTER TABLE 语句与 FOREIGN KEY 约束“FK_GameSchedule_Teams”冲突。冲突发生在数据库“sll_2009”、表“dbo.Teams”、列“TeamID”中。

【问题讨论】:

  • 您是否为这些关系指定了删除和更新规则?
  • 您可能有不符合您尝试添加的约束的现有数据。
  • 更多信息:我创建了一个空的 playpen 数据库,我能够创建两个表和所有关系,问题是在真实的数据库中,我有现有的记录,它不会'不要让我建立关系。
  • 我没有为这些关系指定删除或更新规则,我会在 GameSchedule 级联删除中指定。
  • 删除 On Delete 和 On Update 规则清除了我的错误。

标签: sql-server entity-relationship foreign-key-relationship


【解决方案1】:
create table GameSchedule (
      GameID     integer not null
    , HomeTeamID integer not null
    , AwayTeamID integer not null
);

alter table GameSchedule
  add constraint pk_gsch  primary key (GameID)
, add constraint fk1_gsch foreign key (HomeTeamID) references Teams (TeamID)
, add constraint fk2_gsch foreign key (AwayTeamID) references Teams (TeamID)
;

【讨论】:

  • Msg 547, Level 16, State 0, Line 1 ALTER TABLE 语句与 FOREIGN KEY 约束“fk1_gsch”冲突。冲突发生在数据库“sll_2009”、表“dbo.Teams”、列“TeamID”中。
  • 好吧,我解决了这个问题,我不得不取消选中该框:检查创建时的现有数据:(设置为“否”)并且它有效!谢谢。
  • @Eric,不知道您实际上有一些数据。错误意味着您有一些 HomeTeamID 值在 Teams 表中不存在。
  • 优秀的达米尔;我确实有一些孤儿记录!我删除了它们,一切都很好,谢谢大家的帮助。当我创建空表时,我就知道出了点问题,而且效果很好。
猜你喜欢
  • 2018-06-13
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 2016-08-19
相关资源
最近更新 更多