Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have two Tables in my SQL Server.
One is ApplicationUser and the other is UserApprovals.
These two Tables are related with Foreign key from UserApprooval.UserId to ApplicationUser.UserId.
Now I need to DELETE a record; and I start to do it from ApplicationUser, I don't know if that is right because trow an error:
[ The DELETE statement conflicted with the REFERENCE constraint  FK_UserApprovals_ApplicationUser   The conflict occurred in database  ekkerossDB  table  dbo UserApprovals  column UserID 
The statement has been terminated  ]\r\n UpdateApplicationRejectedUser


What I have tried:

I think the right is to DELETE first the UserApprovals and next the ApplicationUser (if that is necessary.
Did some one can assist me on that??
Posted
Updated 10-Dec-18 0:02am

Yes, you should delete anything that refers back to the ApplicationUser first i.e. any row that has a foreign key must go before the row with that primary key is removed... if referential integrity[^] is switched on.

You can get SQL to do much of the work for you by using Cascade Delete[^]

And don't forget the MSDN documentation Create Foreign Key Relationships | Microsoft Docs[^]
 
Share this answer
 
Comments
Lefteris Gkinis 10-Dec-18 6:11am    
Thank you very much. Your answer was ideal
The DELETE has to start from the Bottom level to Upper Level
CHill60 10-Dec-18 8:27am    
Glad to have helped
If you can't get it working in a normal way, you can use this as a last resort:
-- Disable Constraints at DB level
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
DELETE FROM ApplicationUser
GO
-- Enable Constraints at DB level
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO
The example shown is for use in SQL Server Management Studio.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900