-2

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?

Kevin Hogg
  • 1,771
  • 25
  • 34
Smoking monkey
  • 323
  • 1
  • 6
  • 22

3 Answers3

1

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?

Community
  • 1
  • 1
NoobEditor
  • 15,563
  • 19
  • 81
  • 112
0

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.

dean
  • 9,960
  • 2
  • 25
  • 26
0

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:

  1. Delete all records in referenced tables before deleting from the Branch table
  2. Perform a cascade delete (deleting from the Branch table triggers a delete in every referenced table)
Community
  • 1
  • 1
Kevin Hogg
  • 1,771
  • 25
  • 34
  • You got me right. Very well explained the solution. Thanks a lot . – Smoking monkey Apr 24 '14 at 11:51
  • How to see all the constraints which I made earlier ?. I didn't care about naming them but now I want to apply the cascade delete on all of them . Whenever error comes only then I get to know about their name. – Smoking monkey Apr 24 '14 at 12:09
  • In `SQL Server Management Studio`, in the `Object Explorer`, right-click the table `dbo.Branch` and select `View Dependencies`. The default view `Objects that depend on [Branch]` will show all tables, stored procedures, etc. that depend on the Branch table. – Kevin Hogg Apr 24 '14 at 12:21