Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The ALTER TABLE statement conflicted with the FOREIGN KEY constrain

I'm kind of new to scripting in SQL and I have encountered an error in one of my scripts. The problematic section is:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE dbo.WorkspaceSettings
(
    Id INT NOT NULL IDENTITY PRIMARY KEY ,
        ReportColorRGB1 VARCHAR(15) NOT NULL DEFAULT '61,105,138' ,
    ReportColorRGB2 VARCHAR(15) NOT NULL DEFAULT '180,210,121' 
)

GO

ALTER TABLE Workspace ADD WorkspaceSettingsId int NOT NULL default 1;

GO
ALTER TABLE Workspace
ADD CONSTRAINT FK_WorkspaceSettings_Workspace
FOREIGN KEY (WorkspaceSettingsId)
REFERENCES WorkspaceSettings(Id);
GO

And receive the following error message:

Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_WorkspaceSettings_Workspace". The conflict occurred in database "ClearRisk2_0", table "dbo.WorkspaceSettings", column 'Id'.

Can someone please tell me where I'm going wrong?

like image 349
ErnieStings Avatar asked Feb 01 '11 17:02

ErnieStings


People also ask

How do you fix the Update statement conflicted with the foreign key constraint?

Another solution can be, disable the Foreign Key constraint, update the records and finally enable the Foreign key again. I used below statement to disable Foreign Key constraint on dbo. Orders table. I execute below script to Enable Foreign Key Constraint on dbo.

What is the insert statement conflicted with the foreign key constraint?

You can get this error when you want to inset data into a table that has the Foreing Key. It means that there is no relevant record in the Primary table that Foreign Key is linked to. The record must first be added to the primary table.

How can check foreign key constraint in SQL Server?

Using SQL Server Management Studio Open the Table Designer for the table containing the foreign key you want to view, right-click in the Table Designer, and choose Relationships from the shortcut menu. In the Foreign Key Relationships dialog box, select the relationship with properties you want to view.

What is Nocheck constraint SQL Server?

WITH NOCHECK does so without checking existing data. So the confusing syntax WITH NOCHECK CHECK CONSTRAINT enables a constraint without checking existing data. From the manual: Specifies whether the data in the table is or is not validated against a newly added or re-enabled FOREIGN KEY or CHECK constraint.


1 Answers

The default value of 1 that you've specified for the Workspace.WorkspaceSettingsId column does not yet exist in your WorkspaceSettings table, hence the FK violation.

like image 198
Joe Stefanelli Avatar answered Oct 07 '22 18:10

Joe Stefanelli