這裏是主表:爲什麼有外鍵衝突
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
我得到這個錯誤:
Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Control_cReport_cReportTech". The conflict occurred in database "WHAnalysis", table "dbo.Control_cReportTech", column 'ReportTechKey'. The statement has been terminated.
...我認爲'[ProcessKey] = 12'等於'12作爲ProcessKey'?! – whytheq
@whytheq不同之處在於我指定了'INSERT'中的列'INSERT INTO [Control_cReport](ProcessKey,ReportTechKey)',你不是那麼不知道該把值放在哪裏 – Taryn
ahhh -nice一;只是在'SELECT'子句中按正確的順序放置這些列是可行的,但如果將來使用你的方法,那麼代碼將更具防禦性,因爲它避免了模式更改的問題 – whytheq