Groups | Blog | Home
all groups > sql server programming > february 2004 >

sql server programming : Restrict deleting the Master records


Prabhat
2/9/2004 10:17:37 PM
Hi ALL!

I have 2 tables.
1) Dept = The Master Table (DeptID, DName, Loc) where DeptID is the Primary
Key
2) Emp = The Detail Table(EmpID, DeptID, EName, Sal) Where EmpID is the
Primary Key And DeptID is the Foreign Key to Dept(DeptID)

I have a Stored Procedure to Delete the Record from DEPT Table.
The Below is the Code Snipet of that:

-----------------
DELETE FROM DEPT WHERE DEPTID = @DEPTID

SET @ERR_NUM = @@ERROR
IF (@ERR_NUM <> 0) GOTO HANDLE_ERROR
--------------

But My problem is that If I Delete a Record from Dept Table which has a
Detail record in EMP table then My Constraint Executes and Raise the ERROR.
That I am Not able to Catch in my Stored procedure. So How Do I Handle Such
Type of Error in Stored Procedure?

Please Help.

Thanks
Prabhat


Andrew John
2/10/2004 6:19:05 AM
Prabhat,

Either remove the foreign key and use triggers to enforce referential integrity
or better change the foreign key definition to perform delete cascades. Something
like:

create table Dept
(
DeptID int primary key,
DName varchar(30),
Loc varchar(30)
)

create table Emp
(
EmpID int primary key,
DeptID int foreign key references Dept(DeptID) ON DELETE CASCADE,
EName varchar(30),
Sal money
)

Or just tick the appropriate box in Enterprise Manager on the foreign key.

Regards
AJ

[quoted text, click to view]

Prabhat
2/10/2004 7:57:28 PM
Thanks John,
But I don't want to Cascade the Detail record. I Just wanted to Restrict
deletion of the Master Record if Detail Exists.

Thanks
Prabhat

[quoted text, click to view]

Andrew John
2/11/2004 7:17:53 AM
Prabhat,

Then something like:

Delete d
from Dept d
left outer join Emp e
on e.DeptID = d.DeptID
where e.DeptID is NULL
and d.DeptID = @DeptID

or use NOT EXISTS

DeleteDept
where .DeptID = @DeptID
and not exists ( Select DeptID from Emp where DeptID = @DeptID )

Regards
AJ

[quoted text, click to view]

Prabhat
2/11/2004 2:19:09 PM
Thanks John.
I am able to use the NOT EXISTS.

Thanks
Prabhat

[quoted text, click to view]

AddThis Social Bookmark Button