The ALTER TABLE statement conflicted with the FOREIGN KEY constrain - sql

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?

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.

Just add the following phrase after ALter table sattement:
with nocheck
So, it will be:
Use Database_name
Go
ALTER TABLE ResultScan with nocheck
ADD CONSTRAINT FK_ResultScan_ListVM FOREIGN KEY (TypeAnVirus)
REFERENCES ListVM (Id)
ON DELETE CASCADE
ON UPDATE CASCADE
;
GO

Related

How to alter the table to add foreign key constraint referencing primary key of same table

When I try to alter the table to add the foreign constraint, it is throwing the below error
Msg 547, Level 16, State 0, Line 1
The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_ManagerId". The conflict occurred in database "MX_STAG", table "dbo.Sales_US_User", column 'ID'.
I tried the below queries,none of them have worked.
ALTER TABLE SALES_US_USER
ADD CONSTRAINT FK_ManagerId
FOREIGN KEY (ManagerID) REFERENCES SALES_US_USER(id);
ALTER TABLE SALES_US_USER
ADD FOREIGN KEY (ManagerID) REFERENCES SALES_US_USER(id);
Please help
You've got the DDL right. That error is telling you that you have a row with a ManagerId that does not map to an Id. EG
use tempdb
go
drop table if exists sales_us_manager
go
create table sales_us_user(Id int primary key, ManagerId int)
insert into sales_us_user(id,managerId) values (1,2)
ALTER TABLE SALES_US_USER
ADD CONSTRAINT FK_ManagerId
FOREIGN KEY (ManagerID) REFERENCES SALES_US_USER(id);
--Msg 547, Level 16, State 0, Line 12
--The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_ManagerId". The conflict occurred in database "tempdb", table "dbo.sales_us_user", column 'Id'.
select *
from SALES_US_USER
where ManagerId not in
(select id from SALES_US_USER )
You need to delete both table data before updated database with your new migration. One of the common mistakes that you add a FK (foreign key) from table to another while any on these table contains data. The constraint happens because the FK can't be null and while you are adding the new migration the database find that the new column that will be created will be null so, delete the data in both tables first.
The issue got resolved after finding and updating the rows with an an invalid ManagerId, and then created the constraint.

Can I drop a foreign key without using constraint?

ALTER TABLE table1
ADD FOREIGN KEY attrib1 REFERENCES table2(attrib2)
GO
It works - but how can I drop it?
If I try
DROP FOREIGN KEY (attrib1) REFERENCES table2(attrib2)
it says
Incorrect syntax near the keyword 'FOREIGN'.
In SQL Server you need to drop foreign key constraint by using below query:
Query :
ALTER TABLE [dbo].[Table_Name]
DROP CONSTRAINT [Constraint_Name]
Example:
ALTER TABLE [dbo].[SpeakerDetail]
DROP CONSTRAINT [FK_SpeakerId_UserID]

How to set column NOT NULL?

I have a table:
MyTable{
Id int not null;
Name varchar not null;
TypeId int null;
}
Now i want to make my TypeId column is not null.
First fill it with data:
update [dbo].[MyTable]
set [dbo].[MyTable].[TypeId] = 1
where [dbo].[MyTable].[TypeId] is null
And set not null:
go
ALTER TABLE [dbo].[MyTable] ALTER COLUMN [TypeId] BIT NOT NULL;
But get an error:
Msg 5074, Level 16, State 1, Line 1
The object 'FK_MyTable_ObjTypes' is dependent on column 'TypeId'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE ALTER COLUMN TypeId failed because one or more objects access this column.
What to do in this case? I cant use after table if column is FK?
I tried disable constreints:
GO
ALTER TABLE [dbo].[MyTable] NOCHECK CONSTRAINT [FK_MyTable_ObjTypes];
go
ALTER TABLE [dbo].[MyTable] ALTER COLUMN [TypeId] BIT NOT NULL;
GO
ALTER TABLE [dbo].[MyTable] CHECK CONSTRAINT [FK_MyTable_ObjTypes];
But get same error.
Drop and recreate constrains help me. This is my query:
GO
ALTER TABLE [dbo].[MyTable] DROP CONSTRAINT [FK_MyTable_ObjTypes];
go
ALTER TABLE [dbo].[MyTable] ALTER COLUMN [TypeId] INT NOT NULL;
GO
ALTER TABLE [dbo].[MyTable] WITH NOCHECK
ADD CONSTRAINT [FK_MyTable_ObjTypes] FOREIGN KEY ([TypeId]) REFERENCES [dbo].[ObjTypes] ([Id]);
GO
ALTER TABLE [dbo].[MyTable] WITH CHECK CHECK CONSTRAINT [FK_MyTable_ObjTypes];
Your Foreign Key FK_MyTable_ObjTypes references the TypeId column, so changing the column would invalidate the constraints of the FK.
You will need to remove the FK first (script it as a CREATE so you can see what the existing definition is). Then ALTER your column, before recreating the FK using the newly modified column.
Yo can disable the FK 'FK_MyTable_ObjTypes', alter the column and enable again the FK:
How can foreign key constraints be temporarily disabled using T-SQL?

Alter Table Add Column with Default value And FK, that Value no existing in FK Reference Data

This is My Tables :
Member : Id, ....
Product: Id, ....
My Member Table have some values none if them with Id = 0 and I don't want to add any member with Id = 0, So I try to run this Script:
ALTER TABLE [Product]
ADD [Member_Id] BIGINT NOT NULL DEFAULT(0),
CONSTRAINT [FK_Product_Member] FOREIGN KEY ([Member_Id]) REFERENCES [Member];
So There is an Error :
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Product_Member".
So I try this one:
SET IDENTITY_INSERT [Member] ON
INSERT INTO [Member] ([Id]) VALUES (0);
SET IDENTITY_INSERT [Member] OFF
ALTER TABLE [Product]
ADD [Member_Id] BIGINT NOT NULL DEFAULT(0),
CONSTRAINT [FK_Product_Member] FOREIGN KEY ([Member_Id]) REFERENCES [Member];
DELETE FROM [Member] WHERE [Member].[Id] = 0;
Then The new Error is:
The DELETE statement conflicted with the REFERENCE constraint "FK_Product_Member".
If I try to create all Tables again, every thing will be OK of course with lost my Data so need to get backup, create tables and restore data. So Is there any way to alter Table with this situation? what is your suggestion?
The only "value" that you can have in a referencing table, such that the foreign key constraint is not enforced, is NULL. Not 0, or any other magic value.
So the obvious solution is to allow NULLs:
ALTER TABLE [Product]
ADD [Member_Id] BIGINT NULL,
CONSTRAINT [FK_Product_Member] FOREIGN KEY ([Member_Id]) REFERENCES [Member];
your "alter table" is the better way to do this.but at first you are adding the table with value "0" and this is "FOREIGN KEY" but you have not a Member with value "0" so you get error.
the best way as a know is .alter table and then make the true value to the new column and then alter the column and set that to the "FOREIGN KEY"

How to add a column and make it a foreign key in single MySQL statement?

In mysql, can I add a column and foreign key in the same statement? And what is the proper syntax for adding the fk?
Here is my SQL:
ALTER TABLE database.table
ADD COLUMN columnname INT DEFAULT(1),
FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE;
...and the accompanying error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE' at line 4
Try this:
ALTER TABLE database.table
ADD COLUMN columnname INT DEFAULT(1),
ADD FOREIGN KEY fk_name(fk_column) REFERENCES reftable(refcolumn) ON DELETE CASCADE;
The following query adds a column by alter query and the constraint query makes it a FK in a single mysql query. You can do it like this,
SYNTAX:
ALTER TABLE `SCHEMANAME`.`TABLE1`
ADD COLUMN `FK_COLUMN` BIGINT(20) NOT NULL,
ADD CONSTRAINT `FK_TABLE2_COLUMN` FOREIGN KEY (`FK_COLUMN`)
REFERENCES `SCHEMANAME`.`TABLE2`(`PK_COLUMN`);
EXAMPLE:
ALTER TABLE `USERDB`.`ADDRESS_TABLE`
ADD COLUMN `USER_ID` BIGINT(20) NOT NULL AFTER `PHONE_NUMBER`,
ADD CONSTRAINT `FK_CUSTOMER_TABLE_CUSTOMER_ID` FOREIGN KEY (`USER_ID`)
REFERENCES `USERDB`.`CUSTOMER_TABLE`(`CUSTOMER_ID`);
This can be simplified a bit. You just need to add the "ADD" keyword before "FOREIGN KEY". Adding example below.
ALTER TABLE database.table
ADD COLUMN columnname INT DEFAULT(1),
ADD FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE;
You can use it.
ALTER TABLE database.table
ADD COLUMN columnname INT DEFAULT(1);
ALTER TABLE database.table add FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE;