I’m brand new to SQL and I’m trying to understand the following script.
could someone break this down for me?
ErrorHandler:
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RAISERROR('Error occurred in script to update version: transaction rolled back', 182, 4)
END
ELSE
COMMIT
I have knowledge of Java, so I understand for loops.
It’s the SQL syntax that I need help with.
- For example, what does the double @ symbol represent?
- ROLLBACK TRANSACTION – these are SQL reserved keywords?
- What does ELSE COMMIT mean?
Thank you,
Ray
The stucture of the block is as follows:
So this is a basic condition written in t-sql (no relation with java :)).
The
BEGINandENDtokens are just delimiters, and are used just like{and}in java – that’s why they are used in the IF branch (two commands) and are not used in the else branch (a single command – not mandatory)The @@Error (and other variables begining with @@, like @@ROWCOUNT) are system variables. @@Error specifically contains the last error code given by a command, and it is checked in the snippet to see if everything went OK.
If there are errors, two actions are taken
– a ROLLBACK TRANSACTION command is issued, reversing all changes made to the database (since the last BEGIN TRANSACTION)
– an error is raised no notify the caller of the abnormal termination of the code.
Here the constants (182 and 4) are used for the parameters of the RaiseError call @severity and @state. I suspect that the 182 is a typo, because @severity should be a number in the 0-25 range, and (by convention) 18 is used for a “high severity user error”. The @state param is just some data you can add to the call, to help distinguish between multiple error messages.
If there are no errors, a single COMMIT TRANSACTION is issued, that makes all changes (since the last BEGIN TRANSACTION) permanent and available to all other users of the data.