SQL - INSERT语句与FOREIGN KEY约束冲突 - 值已在父表中

时间:2015-03-06 20:36:58

标签: sql-server insert sql-insert

我知道这个问题被问了一百万次,但我已经检查过,加倍了,并且我的父表中已经存在相应值的三倍。我正在尝试填充我的专辑和艺术家之间的桥牌表,这两者都已填充。在自动填充的C#程序中出现错误后,我尝试手动插入单个值,但仍然出现INSERT错误。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Album](
    [Album ID] [int] IDENTITY(1,1) NOT NULL,
    [Album Title] [nchar](50) NOT NULL,
    [Release Year] [int] NULL,
 CONSTRAINT [PK_Album] PRIMARY KEY CLUSTERED 
(
    [Album 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
/****** Object:  Table [dbo].[Album-Artists]    Script Date: 3/6/2015 12:49:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Album-Artists](
    [Album ID] [int] NOT NULL,
    [Artist ID] [int] NOT NULL,
 CONSTRAINT [PK_Album-Artists] PRIMARY KEY CLUSTERED 
(
    [Album ID] ASC,
    [Artist 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

/****** Object:  Table [dbo].[Artists]    Script Date: 3/6/2015 12:49:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Artists](
    [Artist ID] [int] IDENTITY(1,1) NOT NULL,
    [Artists Name] [nchar](20) NOT NULL,
 CONSTRAINT [PK_Artists] PRIMARY KEY CLUSTERED 
(
    [Artist 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

GO
ALTER TABLE [dbo].[Album-Artists]  WITH CHECK ADD  CONSTRAINT [FK_Album-Artists_Album] FOREIGN KEY([Album ID])
REFERENCES [dbo].[Album] ([Album ID])
GO
ALTER TABLE [dbo].[Album-Artists] CHECK CONSTRAINT [FK_Album-Artists_Album]
GO
ALTER TABLE [dbo].[Album-Artists]  WITH CHECK ADD  CONSTRAINT [FK_Album-Artists_Artists] FOREIGN KEY([Album ID])
REFERENCES [dbo].[Artists] ([Artist ID])
GO
ALTER TABLE [dbo].[Album-Artists] CHECK CONSTRAINT [FK_Album-Artists_Artists]
GO

enter image description here

enter image description here

enter image description here

(我曾尝试使用和不使用表格量词(艺术家。[艺术家ID]等))

1 个答案:

答案 0 :(得分:3)

您的外键正在尝试将ArtistId与AlbumId匹配。

这是不正确的。你需要重新创建它。

ALTER TABLE dbo.[Album-Artists]
  DROP CONSTRAINT [FK_Album-Artists_Artists];

ALTER TABLE [dbo].[Album-Artists]
  WITH CHECK ADD CONSTRAINT [FK_Album-Artists_Artists] 
  FOREIGN KEY([Artist ID]) REFERENCES [dbo].[Artists] ([Artist ID]); 

插入的正确语法是

INSERT INTO [dbo].[Album-Artists]
                         ([Album ID], [Artist ID])
VALUES        (10, 3);

虽然dot-separated prefixes are currently ignored in the column list for INSERT statements

最后,我会避免在对象名称中使用空格或-,因此您不必持续使用带引号的标识符或方括号,并且可以使用不带引号的表单。

INSERT INTO dbo.AlbumArtists
            (AlbumId, ArtistId)
VALUES      (10, 3);