Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cancel a Delete in SQL

Tags:

tsql

triggers

I want to create a trigger to check what is being deleted against business rules and then cancel the deletion if needed. Any ideas?

The solution used the Instead of Delete trigger. The Rollback tran stopped the delete. I was afraid that I would have a cascade issue when I did the delete but that didn't seem to happen. Maybe a trigger cannot trigger itself.

like image 217
Leo Moore Avatar asked Oct 29 '08 10:10

Leo Moore


1 Answers

The solution used the Instead of Delete trigger. The Rollback tran stopped the delete. I was afraid that I would have a cascade issue when I did the delete but that did'nt seem to happen. Maybe a trigger cannot trigger itself. Anyhow, thanks all for your help.

ALTER TRIGGER [dbo].[tr_ValidateDeleteForAssignedCalls]
on [dbo].[CAL]
   INSTEAD OF DELETE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @RecType VARCHAR(1)
    DECLARE @UserID VARCHAR(8)
    DECLARE @CreateBy VARCHAR(8)
    DECLARE @RecID VARCHAR(20)

    SELECT @RecType =(SELECT RecType FROM DELETED)
    SELECT @UserID =(SELECT UserID FROM DELETED)
    SELECT @CreateBy =(SELECT CreateBy FROM DELETED)
    SELECT @RecID =(SELECT RecID FROM DELETED)

     -- Check to see if the type is a Call and the item was created by a different user
    IF @RECTYPE = 'C' and not (@USERID=@CREATEBY)

    BEGIN
        RAISERROR ('Cannot delete call.', 16, 1)
        ROLLBACK TRAN
        RETURN
    END

     -- Go ahead and do the update or some other business rules here
    ELSE
        Delete from CAL where RecID = @RecID    

END
like image 147
Leo Moore Avatar answered Sep 30 '22 17:09

Leo Moore