Conflict of the DELETE statement with the restriction REFERENCE - sql

When I try to excecute this code, I'm getting error:
Conflict of the DELETE statement with the restriction REFERENCE "FK_Options_users". The conflict occurred in database "WINTOUR", table "PrintForm.Options", column 'user_code'
Can't understand why and how to fix that.
declare
#USER_CODE int;
select
#USER_CODE = 24;
delete from Settings.Items where user_code = #USER_CODE
delete from usnet where code = #USER_CODE
delete from usgroups where usercode = #USER_CODE
delete from users where code = #USER_CODE

It seems like Foreign Key constraint exists between the user_code column in PrintForm.Options and the code/user_code column in given tables.
If you try to delete all the data in given tables an error will occur as the user_code column in PrintForm.Options reference the data in the any one of the table from which yor are deleting the data.
To resolve the issue you should either drop and recreate the constraint FK_Options_users or delete the data from child table PrintForm.Options that the Foreign Key references ie where user_code = 24.

It looks to me like you are removing user 24, but the PrintForm.Options table has an entry that is still using it, and were it to be deleted, the foreign key would no longer be satisifed.
Have you perchance missed "Printform.Options" from the list of delete queries?

You have a foreign key relation with one of the rows you are trying to delete. That means that the key is used in another table. You must delete in the correct order so that does not happen.
You are missing a delete for the elements in specified in the error. So in Database WINTOUR in the table PrintForm.Options the use_code is a foreign key to the usercode you are deleting.
so you need to add
delete from PrintForm.Options where user_code = #USER_CODE
probably right before or after Settings.Items.

Related

How can this SQL statement throw the following exception?

how can this statement:
DELETE FROM passage
WHERE passageid NOT IN
(
SELECT passageid from PreEndedPassages_passages
UNION SELECT fromPassageid from severalvisit
UNION SELECT toPassageid from severalvisit
UNION SELECT registerPassageid from stationobjects WHERE registerpassageid IS NOT NULL
UNION SELECT beginPassageid from stationobjects WHERE beginPassageid IS NOT NULL
UNION SELECT endPassageid from stationobjects WHERE endPassageid IS NOT NULL
)
throw this exception?
The DELETE statement conflicted with the FOREIGN KEY constraint "FK_statobj_begpasid". The conflict occurred in database "db.mdf", table "dbo.stationobjects", column 'beginpassageid'.
I have no clue, but it happened. beginPassageId is a foreign key on passageid.
EDIT:
Consider the NOT IN. I want to delete all passages that don't exist in one of its related tables. It usually works, but it happened once.
Thank you.
It means passage is parent table. and stationobjects is child table. You are trying to remove passageid from passage table which is present in stationobjects table as well.
First try to remove those passageid from stationobjects and then you can run this delete statement.
Alternate approach is cascade delete, if your DB supports that.
this kind of occur when you have a foreign key relationship in the two table.
This violates the Refrential Integrity .
so if you delete record from the primary table and record exist in foreign key table,
then you have two options:
1. either set the delete rule to cascade so that when ever you delete primary record the foreign key table record will get automatically deleted.
2.delete record from foreign key table first then from primary key table.
These kind of errors come up when table A foreign key is table B primary key and when you try to delete record in table A that has linking in table B, then deletion will not happen. Try dropping foreign key relation before delete. Same way truncate is used in tables by dropping fk relations and rebuilding them again after the table is reset

How to not to delete if record exists as a foreign in another table?

I have 2 tables. If I delete a record from table1 then first query should check if it's pk exists as a foreign key in table2 then it should not delete the record else it should.
I used this but throwing syntax error
DELETE FROM Setup.IncentivesDetail
INNER JOIN Employee.IncentivesDetail ON Setup.IncentivesDetail.IncentivesDetailID = Employee.IncentivesDetail.IncentiveDetail_ID
WHERE Setup.IncentivesDetail.IncentivesDetailID= #IncentivesDetailID
AND Employee.IncentivesDetail.IncentiveDetail_ID= #IncentivesDetailID
UPDATE:
Based on the answers below I have done this, is it correct ?
If Not Exists(Select * from Employee.IncentivesDetail where IncentivesDetail.IncentiveDetail_ID= #IncentivesDetailID)
Begin
Delete from Setup.IncentivesDetail
WHERE Setup.IncentivesDetail.IncentivesDetailID= #IncentivesDetailID
End
Else
Begin
RAISERROR('Record cannot be deleted because assigned to an employee',16,1)
RETURN
End
Maybe like this?
DELETE FROM Setup.IncentivesDetail
WHERE Setup.IncentivesDetail.IncentivesDetailID= #IncentivesDetailID
AND NOT EXISTS(SELECT 1 FROM Employee.IncentivesDetail WHERE IncentiveDetail_ID= #IncentivesDetailID)
But I must admit, this smells a bit... Are you doing a clean up or ist this something you are doing regularely?
What you are describing is the definition of the foreign key constraint.
If you already have a foreign key between these tables, make sure it's not marked as ON DELETE CASCADE.
If it is, you should delete it and re-create it without that ON DELETE CASCADE see this link from MSDN for details.
If you don't already have a foreign key constraint, you need to create one:
ALTER TABLE Setup.IncentivesDetail
ADD CONSTRAINT FK_Setup_IncentivesDetail_IncentivesDetailID FOREIGN KEY (IncentivesDetailID)
REFERENCES Employee.IncentivesDetail (IncentiveDetail_ID )
;

Deleted foreign key reference, still get error when deleting

I have a web app that calls an sql script that is trying to delete a row from table_1. However, table_2 references it with an FK constraint, so this was giving an error. I manually deleted the referencing row of table_2. (I confirmed via query that it's gone.) Then I ran the app and I still get the same error! (The DELETE statement conflicted with the REFERENCE constraint "table_2_fk". The conflict occurred in database "my_db", table "table_2", column 'table_1_pk'.
Why?
Table info
table_2 has columns pk, name, and table_1_pk. It has an FK constraint table_2_fk that ensures that table_1_fk = table_1.pk
table_1 has pk, a bunch of other columns, and no FK constraint.
details of delete and query
Suppose that table_1.pk = 1. I ran the statement
delete from table_2 where table_1_pk = 1
I then queried the db:
select * from table_2 where table_1_pk = 1
This returned 0 results.
You should change your code so that you delete from table 2 first, then delete from table 1. Or optionally add a Cascade delete to you foreign key constraint (automatically deletes from table 2 when a delete is made in table 1)
ADD CONSTRAINT [FK_Table2_table1] FOREIGN KEY([table_1_pk])
REFERENCES [dbo].[table1] ([table_1_fk ])
ON DELETE CASCADE

Unable to delete a row from a table due to a dependency/reference in another table

I have a stored procedure that deletes a record from a table where one of the columns matches a specified value:
ALTER PROCEDURE [dbo].[Sp_DelBranch] #datafield varchar(50)
AS
BEGIN
DELETE FROM Branch WHERE branchname = #datafield
END
Unfortunately I get the following error on execution:
The DELETE statement conflicted with the REFERENCE constraint "fk_BranchIdDept". The conflict occurred in database "MproWorkSpace", table "dbo.Department", column 'BranchId'.
Can anyone explain why I'm seeing this error?
conflicted with the REFERENCE constraint "fk_BranchIdDept".
This means, that the value you are trying to delete, is primary key in some other table and is referenced in this table as foreign key,i.e., a primary-foreign key relation is mapped through constraint fk_BranchIdDept ...So unless you delete the referred primary key, foreign key can not be removed from table.
Otherwise, this will lead to data inconsistency!
Look for Cascade Delete to help you in this!
SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?
The DELETE statement conflicted with the REFERENCE constraint "fk_BranchIdDept".
The record you're trying to delete is referenced in other tables; deleting the Branch record would leave the other tables orphaned, and referencing something that no longer exists.
There are two approaches to this:
Delete all records in referenced tables before deleting from the Branch table
Perform a cascade delete (deleting from the Branch table triggers a delete in every referenced table)
The error means that there are some rows in Department table referencing the branch you're trying to delete.
You should either delete the corresponding rows from the Department table first, or change values in BranchId column for these rows, so they point to some other branch.

Error Adding Multiple FK Relationship in SQL Server 2008

Consider we have two tables ProductType and ProductSizeGroup as below
ProductType
Id
Name
MaleSizeGroupId
FemaleSizeGroupId
ChildSizeGroupId
ProductSizeGroup
Id
Name
Each of MaleSizeGroupId, FemaleSizeGroupId and ChildSizeGroupId fields should be FKs to ProductSizeGroup.Id.
I add one using the following statement:
ALTER TABLE [dbo].[ProductType]
WITH CHECK ADD CONSTRAINT
[FK_ProductType_ProductSizeGroup_Male] FOREIGN KEY([MaleGroupId])
REFERENCES [dbo].[ProductSizeGroup] ([Id])
This works fine. I try to add the next using
ALTER TABLE [dbo].[ProductType]
WITH CHECK ADD CONSTRAINT
[FK_ProductType_ProductSizeGroup_Female] FOREIGN KEY([FemaleGroupId])
REFERENCES [dbo].[ProductSizeGroup] ([Id])
But I get the error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_ProductType_ProductSizeGroup_Female". The conflict
occurred in database "dbname", table "dbo.ProductSizeGroup", column
'Id'.
So there is conflict.. but what conflict? What should I be looking for?
That just means: there are rows in your table ProductType that have values in the FemaleGroupId column which do not exist in the referenced table (ProductSizeGroup).
It's not a problem per se - you can totally have multiple columns going from one table to another.
The problem is with the existing data - you have data in there that doesn't live up to that FK constraint. Fix that data and you should be fine.
To find those offending rows, use a query like this:
SELECT *
FROM [dbo].[ProductType]
WHERE FemaleGroupId NOT IN (SELECT DISTINCT Id FROM [dbo].[ProductSizeGroup])
That will list all offending rows - update their attribute and get going again!