I have a table inheritance in my database. I have table “Item” and Table “Something“. Item has ItemId which is primary key and auto increment. In table Something I have ItemId which is primary key (not autoincrement). Theese tables are in 1:1 relation.
So I have tried to insert data in those tables but this doesn’t work:
...
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)
...
This is the error that I get:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Items_Somethings".
Tables create script:
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
Bad Direction of foreign key.
You should add foreign key to [dbo].[Somethings] and reference [dbo].[Items].ItemId
Like this: