2011-10-16 157 views
0

嗨,INSERT語句與FOREIGN KEY約束衝突,即使它爲空?

我有一個包含外鍵值(id)的表。此字段可以爲空,但問題是,我得到下面的異常,如果我將它設置爲null:

INSERT語句衝突與外鍵約束

爲什麼?它可爲空

EDIT1:

USE [biss] 
GO 

/****** Object: Table [dbo].[VoucherCodes] Script Date: 10/16/2011 19:55:16 ******/ 
SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

CREATE TABLE [dbo].[VoucherCodes](
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    [Code] [nvarchar](50) NOT NULL, 
    [StartDate] [datetime] NOT NULL, 
    [EndDate] [datetime] NOT NULL, 
    [InactivatedDate] [datetime] NULL, 
    [AdCategoryId] [int] NULL, 
CONSTRAINT [PK_VoucherCodes] PRIMARY KEY CLUSTERED 
(
    [Id] 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 

ALTER TABLE [dbo].[VoucherCodes] WITH CHECK ADD 
    CONSTRAINT [FK_VoucherCodes_AdCategories] FOREIGN KEY([AdCategoryId]) 
    REFERENCES [dbo].[AdCategories] ([Id]) 
    ON UPDATE SET NULL 
GO 

ALTER TABLE [dbo].[VoucherCodes] CHECK CONSTRAINT [FK_VoucherCodes_AdCategories] 
GO 

ALTER TABLE [dbo].[VoucherCodes] WITH CHECK ADD 
    CONSTRAINT [FK_VoucherCodes_VoucherCodes] FOREIGN KEY([Id]) 
    REFERENCES [dbo].[VoucherCodes] ([Id]) 
GO 

ALTER TABLE [dbo].[VoucherCodes] CHECK CONSTRAINT [FK_VoucherCodes_VoucherCodes] 
GO 

ALTER TABLE [dbo].[VoucherCodes] WITH CHECK ADD 
    CONSTRAINT [FK_VoucherCodes_VoucherCodes1] FOREIGN KEY([Id]) 
    REFERENCES [dbo].[VoucherCodes] ([Id]) 
GO 

ALTER TABLE [dbo].[VoucherCodes] CHECK CONSTRAINT [FK_VoucherCodes_VoucherCodes1] 
GO 

ALTER TABLE [dbo].[VoucherCodes] ADD 
    CONSTRAINT [DF_VoucherCodes_Inactive] DEFAULT ((1)) FOR [InactivatedDate] 
GO 
+0

架構和錯誤消息,將是有益的。 – GriffinHeart

+0

表中沒有其他外鍵? (只是爲了確保...) –

+0

什麼是失敗的代碼?你可以添加完整的CREATE TABLE嗎 – gbn

回答

5

你的外鍵來自兩個自參考圓形FK約束。

你有ID列作爲自己的FK:當然他們將失敗,因爲他們不會存在於INSERT時間。

運行此

ALTER TABLE [dbo].[VoucherCodes] 
    DROP CONSTRAINT FK_VoucherCodes_VoucherCodes, FK_VoucherCodes_VoucherCodes1 
相關問題