Here is the main table:
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
Here is the secondary table:
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
I’ve then added to the secondary table:
INSERT INTO [WHAnalysis].[dbo].Control_cReportTech
VALUES
(1,'Excel Macros'),
(2,'VB Script'),
(3,'PDF'),
(4,'Batch')
Now I’m attempting to INSERT some data from an old table into the main table via this:
INSERT INTO [WHAnalysis].[dbo].[Control_cReport]
SELECT
[ProcessKey] = 12,
[ReportTechKey] = 1
FROM WHAnalysis.dbo.Controltb_ReportingScheduler_jq
I get this error:
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.
The issue is because you are attempting to
INSERTa value in theProcessKeyfield, that does not exist in theControl_cReportTechtable.I would alter the
INSERTstatement to specify the fields that you are trying toINSERTinto:See SQL Fiddle With Demo
Use the above query instead of your current query because when the columns are not specified, it attempts to insert the values in the order of the table structure. So it is attempting to insert a value of
12into theReportTechKeycolumn which violates the Foreign Key.You are always much better off specifying the order of the columns that you are inserting data into.