0

这是主表:

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”中。该语句已终止。

4

1 回答 1

5

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

我会更改INSERT语句以指定您尝试INSERT进入的字段:

INSERT INTO [Control_cReport] (ProcessKey, ReportTechKey)
SELECT 12 as ProcessKey, 1 as ReportTechKey;
FROM WHAnalysis.dbo.Controltb_ReportingScheduler_jq;

请参阅带有演示的 SQL Fiddle

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

指定要插入数据的列的顺序总是要好得多。

于 2012-10-08T11:10:32.823 回答