Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is my Stored procedure, which On specifying the Department ID, it deletes all the records for that particular ID from the Departments table and it also deletes all the records from the Employees table for that particular department ID.

The condition is to delete record from either both the tables or none.

My code deletes record from one table alone. i dont get where the problem occurs.

Note: There is no foreign key between Employees table and department table.
but there is a foreign key between Employees table and Accounts table.

SQL
CREATE PROCEDURE usp_DeleteDepartment (@DepartmentId INT)
AS

BEGIN TRAN

DELETE FROM Departments_Details
WHERE DepartmentId = @DepartmentId

IF (@@ERROR <> 0) GOTO ERROR 

DELETE FROM Employees_Details
WHERE DepartmentId = @DepartmentId

IF (@@ERROR <> 0) GOTO ERROR 

COMMIT TRAN

ERROR:
IF (@@ERROR <> 0) BEGIN
PRINT 'Foreign key constraint error occurred!'
    ROLLBACK TRAN
END
Posted
Updated 8-Oct-12 21:19pm
v2

you can use try catch instead of @@ERROR.
see below code :

SQL
BEGIN   
   SET NOCOUNT ON;
   BEGIN TRY
      BEGIN TRAN
         /*
            Insert your Code Here.
         */
      COMMIT TRAN
   END TRY
   BEGIN CATCH         
      ROLLBACK TRANSACTION      
   END CATCH
END
 
Share this answer
 
Comments
bolshie6 9-Oct-12 4:16am    
Thank you, I solved it myself. I've also done it in the same way.
SQL
ALTER PROCEDURE usp_DeleteDepartment (@DepartmentId INT)
AS

BEGIN TRANSACTION Trans
BEGIN TRY

DELETE FROM Departments_Details
WHERE DepartmentId = @DepartmentId

DELETE FROM Employees_Details
WHERE DepartmentId = @DepartmentId

COMMIT TRANSACTION Trans
END TRY

BEGIN CATCH
    ROLLBACK TRANSACTION Trans
END CATCH   
 
Share this answer
 

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