1:1表关系无法插入新行

时间:2012-10-07 13:42:32

标签: sql database sql-server-2008 tsql stored-procedures

我的数据库中有一个表继承。我有表“Item”和表“Something”。 ItemItemId 主键和自动增量。在表Something中,我有ItemId 主键(不是自动增量)。 Theese表与 1:1 关系 所以我试图在这些表中插入数据,但这不起作用:

...
DECLARE @itemId int

    INSERT INTO dbo.Items
    (ItemTypeId,UserId,CreatedOnDate,Title,Description)
    VALUES
    (@p_ItemTypeId,@p_UserId,@p_CreatedOnDate,@p_Title,@p_Description)

    SELECT @itemId = SCOPE_IDENTITY()

    INSERT INTO dbo.Something
    (ItemsId)
    VALUES
    (@itemId)
...

这是我得到的错误:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Items_Somethings".

表创建脚本:

CREATE TABLE [dbo].[Items](
    [ItemdId] [int] IDENTITY(1,1) NOT NULL,
    [ItemTypeId] [int] NULL,
    [UserId] [int] NULL,
    [CreatedOnDate] [smalldatetime] NULL,
    [Title] [nvarchar](50) NULL,
    [Description] [nvarchar](max) NULL,

 CONSTRAINT [PK_Items] PRIMARY KEY CLUSTERED 
(
    [ItemId] 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].[Items]  WITH CHECK ADD  CONSTRAINT [FK_Items_Somethings] FOREIGN KEY([ItemId])
REFERENCES [dbo].[Somethings] ([ItemId])
GO

ALTER TABLE [dbo].[Items] CHECK CONSTRAINT [FK_Items_Somethings]
GO


CREATE TABLE [dbo].[Somethings](
    [ItemId] [int] NOT NULL,
 CONSTRAINT [PK_Somethings] PRIMARY KEY CLUSTERED 
(
    [ItemId] 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

2 个答案:

答案 0 :(得分:1)

ALTER TABLE [dbo].[Items]  WITH CHECK ADD  CONSTRAINT [FK_Items_Somethings] FOREIGN KEY([ItemId])
REFERENCES [dbo].[Somethings] ([ItemId])

外键的错误方向。

您应该将外键添加到[dbo]。[Somethings]并引用[dbo]。[Items] .ItemId 像这样:

ALTER TABLE [dbo].[Somethings]  WITH CHECK ADD  CONSTRAINT [FK_Somethings_Items] FOREIGN KEY([ItemId])
REFERENCES [dbo].[Items] ([ItemId])

答案 1 :(得分:1)

在此脚本中,您已反转表之间的继承。如果Something表继承自Item表,那么必须在表'Something'中创建FK,如下所示:

ALTER TABLE [dbo].[Somethings]  WITH CHECK ADD  CONSTRAINT [FK_Somethings_Items] FOREIGN KEY([ItemId])
REFERENCES [dbo].[Items] ([ItemId])
GO

ALTER TABLE [dbo].[Somethings] CHECK CONSTRAINT [FK_Somethings_Items]
GO