2012-10-04 32 views
3

我試圖在與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)) 
+0

我們需要關於FK內表格如何相互關聯的信息。它基於哪個字段? – Beth

+0

您在自動生成的列上定義了一個約束。那不會那樣工作。你必須改變你的表格定義 –

回答

5

如果你想INSERT值到表Articulos並不在表Fabricantes存在,那麼你會得到錯誤的代碼。

由於Codigo字段上有一個外鍵,因此您必須在Fabricantes中具有相同的值。

查看non-working demo。此演示顯示Fabricantes表中不存在Codigo的值,因此它會引發錯誤消息。這是一個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

+0

bluefeet擊敗了我。刪除我的答案,因爲它與此相同。 – rownage

0

我認爲你的錯誤是一個錯誤的外鍵。根據表格的外觀,你應該參考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)) 
+0

謝謝TToni,這很有幫助。現在我試圖在桌面上插入新的日期,Articulos仍然可以。顯然我的錯誤在於兩張表格之間的參考 –