Click here to Skip to main content
15,889,876 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey everyone,

I am using a delete command on a grid,the primary key of this table in the foreign key in an another table.So,i'm getting this exception while performing delete operation--The DELETE statement conflicted with the REFERENCE constrain.How to resolve this.The table from which i'm trying to delete is tblProducts with primary key Pid.And Pid is foreign key to table tblOrderItems.

I saw a solution but can't understand how to use it.It was--

From management studio, right click --> edit, and toward the bottom where it sets the constraints, add "on delete casecade" and execute just the alter.

Help me resolve this.

Thanks
Amit
Posted
Comments
Rod Kemp 27-Oct-10 7:33am    
This is just a bad idea, you would be deleting order items also are the primary keys to the order items tables used anywhere and so on.
Normal solution for this sort of thing is to set a "deleted" flag.
AmitChoudhary10 27-Oct-10 7:36am    
how can i do this?..i am getting exception while deleting item.

First you should delete reference key table record and then delete primary key record Like

delete tblOrderItems where Pid = 'p100';
delete tblProducts where pid = 'p100';
 
Share this answer
 
Comments
AmitChoudhary10 28-Oct-10 8:04am    
that means for deleting row from this table,i'll have to delete all the rows from different tables where its primary key is referenced?...
Yes you must delete reference table row first then only you can able to delete primary key table record ....
 
Share this answer
 
Comments
AmitChoudhary10 28-Oct-10 8:27am    
i am using this query,its not working,i want to delete from tblProducts,could you help a bit--

"DELETE FROM tblProducts AS P INNER JOIN tblOrderItems AS OI ON OI.Pid = P.Pid where Pid=@Pid"
AmitChoudhary10 28-Oct-10 8:29am    
its giving exception "INCORRECT syntax near AS"
Create a Procedure or run the below procedure on your machine it will work
No need inner join for deleting reference key u can just delete as it is

SQL
Create Procedure DeleteProduct
@PID varchar(100)
AS
begin transaction
DELETE tblOrderItems where Pid=@PID
DELETE tblProducts where Pid=@PID
IF @@error <> 0
BEGIN
ROLLBACK
END
ELSE
BEGIN
COMMIT
END
 
Share this answer
 
v2
Comments
AmitChoudhary10 28-Oct-10 8:43am    
still not working.Stored procedure is giving errors

USE [ChalkHill]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spDeleteItem]
@Pid = varchar(100)

As
begin transaction
SET NOCOUNT ON;
DELETE tblOrderItems where Pid=@Pid
DELETE tblProducts where Pid=@Pid
IF @@error <> 0
BEGIN
ROLLBACK
END
ELSE
BEGIN
COMMIT
END
AmitChoudhary10 28-Oct-10 8:51am    
my bad,thats done,thanks man :-)

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