0

I am calling a HttpDelete API to delete data from my DB via a stored proc.

I have a table called CustomerQueryData like below (lots of columns removed for brevity.

   CustomerQueryId | CustId | CarId | CustName
    1                   1       1       Joe
    2                   2       2       Jane 

Then I have a Car Table like below (CarId on the customerquery data table is a FK to the car table)

CarId | CarName
1        BMW
2        Audi

In the stored PROC I am getting passed The CustId and I need to delete all data associated with that CustId. If I try to delete the Data from CarTable first based on the CustId using a join I can't due to FK constraint. If I delete the CustomerData first based on the ID I pass in it will delete from that table but then I will have an orphaned row in the CarTable because I can't join based on the CustId I am passed it because it won't exist in the CustomerData table anymore.

I know once solution would be to turn off constraints and delete from CarTable and then delete from CustomerData but just wondering is there a better approach I am not thinking off

So my Query that is throwing the FK error is:

  DELETE car FROM [MySchema].[Car] car 
  JOIN MySchema.CustomerQueryData cqd on car.CarId = cqd.CarId 
  where cqd.CustId = 2

which throws - The DELETE statement conflicted with the REFERENCE constraint

Ctrl_Alt_Defeat
  • 3,933
  • 12
  • 66
  • 116

0 Answers0