为什么会出现外键冲突

时间:2012-10-08 10:59:03

标签: sql sql-server sql-server-2008-r2

这是主表:

CREATE TABLE [dbo].[Control_cReport](
    [ReportKey] [int] IDENTITY(10000,1) NOT NULL,
    [ReportTechKey] [int] NOT NULL,
    [ProcessKey] [int] NULL,
 CONSTRAINT [PK_Control_cReport] PRIMARY KEY CLUSTERED 
(
    [ReportKey] 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].[Control_cReport]  WITH CHECK ADD CONSTRAINT [FK_Control_cReport_cReportTech] FOREIGN KEY([ReportTechKey])
REFERENCES [dbo].[Control_cReportTech] ([ReportTechKey])
GO

ALTER TABLE [dbo].[Control_cReport] CHECK CONSTRAINT [FK_Control_cReport_cReportTech]
GO

ALTER TABLE [dbo].[Control_cReport] ADD  DEFAULT ((12)) FOR [ProcessKey]
GO

这是次要表:

CREATE TABLE [dbo].[Control_cReportTech](
    [ReportTechKey] [int] NOT NULL,
    [ReportTechDescription] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK__Control_cReportTech] PRIMARY KEY CLUSTERED 
(
    [ReportTechKey] 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

然后我添加到辅助表中:

INSERT INTO [WHAnalysis].[dbo].Control_cReportTech  
VALUES  
    (1,'Excel Macros'),
    (2,'VB Script'),
    (3,'PDF'),
    (4,'Batch')

现在我试图通过这个INSERT将旧表中的一些数据导入主表:

INSERT INTO [WHAnalysis].[dbo].[Control_cReport]
SELECT
    [ProcessKey] = 12,
    [ReportTechKey] = 1
FROM WHAnalysis.dbo.Controltb_ReportingScheduler_jq

我收到此错误:

  

消息547,级别16,状态0,行1 INSERT语句冲突   使用FOREIGN KEY约束“FK_Control_cReport_cReportTech”。该   数据库“WHAnalysis”表中发生冲突   “dbo.Control_cReportTech”,列“ReportTechKey”。声明有   已被终止。

1 个答案:

答案 0 :(得分:5)

问题是因为您试图在INSERT字段中ProcessKey Control_cReportTech INSERT表中不存在的值。

我会更改INSERT语句,以指定您尝试INSERT INTO [Control_cReport] (ProcessKey, ReportTechKey) SELECT 12 as ProcessKey, 1 as ReportTechKey; FROM WHAnalysis.dbo.Controltb_ReportingScheduler_jq; 的字段:

12

请参阅SQL Fiddle With Demo

使用上述查询而不是当前查询,因为未指定列时,它会尝试按表结构的顺序插入值。因此,它试图在ReportTechKey列中插入违反外键的值{{1}}。

最好指定要插入数据的列的顺序。