The DELETE statement conflicted with the REFERENCE

陌路散爱 提交于 2019-12-22 08:17:44

问题


I have a table_Project with a CustomerID in it (linked to tbl_Customer). In tbl_Customer I have Customer_ID(as key) and some other info like Phone, Email etc.

To delete it from the Gridview I use this DeleteCommand:

DeleteCommand="DELETE FROM [tbl_Customer] WHERE [Customer_ID] = @Customer_ID" 

But it gives me the following error:

The DELETE statement conflicted with the REFERENCE constraint "Klant_Relatie". The conflict occurred in database "Database_1", table "dbo.tbl_Project", column 'CustomerID'. The statement has been terminated.

But with updating the CustomerInfo I do not get any error. I have seen different solutions for C# but I use .net

Any idea's?


回答1:


Your problem has something to do with referential integrity. You cannot delete a record (from table tbl_Customer) which is currently being referenced by some records in a certain table (table table_Project for example). UPDATE is different from DELETE unless you are updating the key, in your case CustomerID. UPDATE modifies a record while DELETE removes the record.

Take a look at this example,

tbl_Customer table

CustomerID  CustomerName
1           Hello
2           World

table_Project table

CustomerID  ProjectName
1           Webscripting
1           Database Maintenance

You can always do anything you want on record 2 of table tbl_customer because there is no record that is referencing to it. But in record 1, you can't delete it unless the two records from table table_Project are deleted. You can modify column CustomerName but not CustomerID is if still being referenced.




回答2:


You cannot delete the client if he is referenced by a project.. That's what the error means..

I don't understand your

I have seen different solutions for C# but I use .net

But you have different solutions here:

  1. Change the client referenced by all projects linked to old one (the one you want to delete)
  2. Drop constraint (Not really good option)
  3. Delete project before deleting the client (manually or by using cascade delete)



回答3:


Another thing you could do is in SQL server change the foreign key link so that on delete it cascades. This will cause the records to delete downward. So if you delete a record in table a, any record in table b that references that record will also get deleted.



来源:https://stackoverflow.com/questions/15970893/the-delete-statement-conflicted-with-the-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!