【问题标题】:Why do I get a foreign key constraint error [closed]为什么我会收到外键约束错误 [关闭]
【发布时间】:2012-10-04 19:17:31
【问题描述】:

我正在尝试使用 sql server 2012 在表中插入值,但出现此错误:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Fabricante". 
The conflict occurred in database 
"practica", table "dbo.Fabricantes", column 'Codigo'.

我只有两张桌子。

这是我用来创建表格的代码

create table Fabricantes(
Codigo int identity primary key,
Nombre nvarchar (100) not null)

create table Articulos(
Codigo int identity primary key,
Nombre nvarchar (100) not null,
Precio int,
Fabricante int,
constraint FK_Fabricante foreign key
(Codigo) references Fabricantes (Codigo))

【问题讨论】:

  • 我们需要关于表格在 FK 中如何相互关联的信息。它基于哪些字段?
  • 您在自动生成的列上定义了一个约束。那不会那样工作的。你必须改变你的表定义

标签: sql sql-server sql-server-2012


【解决方案1】:

如果您尝试将INSERT 一个值添加到表Articulos 中,而该值在表Fabricantes 中不存在,那么您将收到错误消息。

由于Codigo 字段上有外键,因此Fabricantes 中的值必须相同。

查看non-working demo。此演示显示Codigo 的值在Fabricantes 表中不存在,因此它会引发错误消息。这是一个working demo,它表明该值首先在表中。

无论如何,我认为您需要重做表格。

create table Fabricantes
(
  Codigo int identity primary key,
  Nombre nvarchar (100) not null
);

create table Articulos
(
  Codigo int primary key,
  Nombre nvarchar (100) not null,
  Precio int,
  Fabricante int,
  constraint FK_Fabricante foreign key
  (Codigo) references Fabricantes (Codigo)
);

您最初将Articulos 表设置为identity,但由于您将该字段作为外键,我认为您不应该在该表上设置identity

【讨论】:

  • bluefeet 打败了我。删除我的答案,因为它与此相同。
【解决方案2】:

我认为你的错误是一个错误的外键。根据表格的外观,您应该像这样将 Articulo.Fabricante 引用到 Fabricante.Codigo:

create table Fabricantes(
Codigo int identity primary key,
Nombre nvarchar (100) not null)

create table Articulos(
Codigo int identity primary key,
Nombre nvarchar (100) not null,
Precio int,
Fabricante int,
constraint FK_Fabricante foreign key
(Fabricante) references Fabricantes (Codigo))

【讨论】:

  • 感谢 TToni,这很有帮助。现在,我试图在 Articulos 表格上插入新日期,一切正常。显然我的错误在于两个表之间的引用
猜你喜欢
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
  • 2022-06-12
  • 1970-01-01
相关资源
最近更新 更多