2016-08-18 173 views
2

我有兩個表與外鍵約束

衝突

琪:

CREATE TABLE [dbo].[R_ACADEMIE](
    [ID_ACADEMIE] [dbo].[IDENTIFIANT] NOT NULL, 
    [LC_ACADEMIE_CODE] [dbo].[LIBELLE_COURT] NOT NULL, 
    [LM_ACADEMIE_LIBELLE] [dbo].[LIBELLE_MOYEN] NOT NULL, 
CONSTRAINT [PK_R_ACADEMIE] PRIMARY KEY NONCLUSTERED 
(
    [ID_ACADEMIE] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 
GO 

我在E_VOYAGEUR表中添加我的專欄

ALTER TABLE E_VOYAGEUR ADD ID_ACADEMIE IDENTIFIANT NOT NULL DEFAULT 0; 

我想創建一個FK在我的E_VOYAGEUR桌上我這樣做:

ALTER TABLE [dbo].[E_VOYAGEUR] WITH CHECK ADD CONSTRAINT [FK_E_VOYAGE_A_VOYAGEU_E_ACADEMIE] FOREIGN KEY([ID_ACADEMIE]) 
REFERENCES [dbo].[R_ACADEMIE] ([ID_ACADEMIE]) 
GO 

我有這樣的錯誤:

The ALTER TABLE statement is in conflict with the FOREIGN KEY constraint " FK_E_VOYAGE_A_VOYAGEU_E_ACADEMIE " . The conflict occurred in database " DEV ", " dbo.R_ACADEMIE " table, column ' ID_ACADEMIE ' .

+2

聽起來好像你在R_ACADEMIE中不存在E_VOYAGEUR中的ID_ACADEMIE值。當引用的表中不存在某個值時,無法將外鍵添加到現有數據中。您將需要插入缺失的值。 – SMM

+0

@SMM我更新了我的文章。在'R_ACADEMIE'中,我有'ID_ACADEMIE' – Mercer

+0

您是否將E_VOYAGEUR.ID_ACADEMIE中的值作爲R_ACADEMIE中的行插入?例如您用'not null default 0'將新列添加到E_VOYAGEUR中...您是否在R_ACADEMIE中有ID_ACADEMIE = 0的記錄? – SMM

回答

3

看來你的表E_VOYAGEUR已經有一些價值觀和你正在改變該表以默認值的新列ID_ACADEMIE添加爲0。 這使列ID_ACADEMIE的值爲0的表E_VOYAGEUR中的所有行。並且,當您向該表添加外鍵約束時,引用表[R_ACADEMIE]在列ID_ACADEMIE中可能沒有值爲'0'的條目,並且似乎是此問題的原因。

在將外鍵添加到表E_VOYAGEUR之前,請確保ID_ACADEMIE列中的值具有表[R_ACADEMIE]中的引用。