Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • SQL Server : Instead of Trigger

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 250
    Comment on it

    A trigger is a special kind of a store procedure that executes in response to specific actions on the table like insertion, updation or deletion. It is a database object which is bound to a table. Triggers cannot be explicitly invoked. The only way to invoke them is by performing the required action on the table that they are assigned to.If there is an INSTEAD OF Trigger attached to a table than it is executed instead of the action query that causes it to fire.For example, if you define an Instead Of trigger on a table for the Delete operation, and than try to delete rows, they will not actually get deleted.

    INSTEAD OF TRIGGERS can be classified as below:

    1) INSTEAD OF INSERT Trigger.

    2) INSTEAD OF UPDATE Trigger.

    3) INSTEAD OF DELETE Trigger.

    Lets create an Instead Of Delete Trigger:

    1. CREATE TRIGGER trgInsteadOfDelete ON [dbo].[FileList]
    2. INSTEAD OF DELETE
    3. AS
    4. declare @fileId int;
    5. declare @fileName varchar(100);
    6. declare @fileSize int;
    7. select @fileId=d.FileID from deleted d;
    8. select @fileName=d.FileName from deleted d;
    9. select @fileSize=d.FileSize from deleted d;
    10.  
    11. BEGIN
    12. if(@fileSize>10)
    13. begin
    14. RAISERROR('Cannot delete file if size exceeds' > 10,16,1);
    15. ROLLBACK;
    16. end
    17. else
    18. begin
    19. delete from FileList where FileID=@fileId;
    20. COMMIT;
    21. insert into FileListAudit(FileID,FileName,FileSize,Action,Timestamp)
    22. values(@fileId,@fileName,@fileSize,'Instead Of Delete Trigger',getdate());
    23. PRINT 'Record Deleted '
    24. end
    25. END
    26. GO

    This trigger will prevent the deletion of records from the table where fileSize > 10. If such a record is deleted,the transaction will be rolled back by the Instead Of Trigger, otherwise the

    transaction will be committed.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: