Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
How to check for error in a trigger?
Message
 
General information
Forum:
Microsoft SQL Server
Category:
Stored procedures, Triggers, UDFs
Environment versions
SQL Server:
SQL Server 2005
Miscellaneous
Thread ID:
01520325
Message ID:
01520327
Views:
33
>Hi,
>
>I am creating my first trigger that will set the value of all foreign keys to empty string ('') when user deleted a row in the parent table.
>
>Here is the draft of my code:
>
>
>ALTER TRIGGER [my_parent_delete] 
>   ON  [dbo].[my_parent_table] 
>   INSTEAD OF DELETE
>AS 
>BEGIN
>    SET NOCOUNT ON;
>
>    DECLARE @C_KEY_VALUE CHAR(10)
>
>    -- Get the value of the key/unique field that user wants to delete.
>    SELECT @C_KEY_VALUE FROM DELETED
>
>    -- Update Child 1
>    UPDATE my_child1_table SET foreign_key_fld = '' WHERE foreign_key_fld = @C_KEY_VALUE
>    -- Update Child 2
>    UPDATE my_child2_table SET foreign_key_fld = '' WHERE foreign_key_fld = @C_KEY_VALUE
>    -- Update Child 3,4, etc.
>
>    -- Now delete this row from the parent table
>   delete from my_parent_table WHERE EXISTS 
>	( SELECT * FROM DELETED WHERE my_parent_table.my_unique_fld = DELETED.my_unique_fld )
>
>END
>
>
>My question is, what if any of the child updates fails, how do I "trap" this error? TIA.

If one of the child update fails, most likely the whole trigger will rollback.
Also, your trigger is written the way that it can only handle 1 record deletion in a parent table. You should at least add some preventive code, e.g.
if (select count(*) from Deleted) >1
  begin
   raiserror ('This trigger can only work with single record deletion!',16,1)
   rollback
   return
  end
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform