BeginTry--sqlEndTrybeginCatch--sql (handle error action) endCatch
We're going to write a possible error in SQL at begin Try...endIf there is an error between the try, the program jumps to the immediately following begin Try...endBeign Catch...end of TryCatch
, perform beign catch...endCatch error handling SQL. Try: Catch can be nested.
At Begin catch ... endIn catch we can use the following four functions provided by the system to get the error message:
Error_number return error code
Error_serverity returns the severity level of the error
Error_state Return Error status code
Error_message returns the complete error message
The above four functions are at the same begin catch ... endA catch can be used more than once, and the value is constant.
Here is a simple little example.
BeginTry Select2/0 EndTry
Begin catch select error_number () Span class= "Apple-converted-space" > as error_number, Error_message () as error_message, Error_ State () as error_state, error _severity () as error_ Severity End catch
-----error_number error_message error_state Error_severity
8134 encountered a divide-by-zero error. 1 16
Not affected by TRY ... CATCH constructs an error that affects the TRY ... Catch constructs do not catch errors in the following situations:
A warning or informational message with a severity level of 10 or less.
Errors that are handled by the SQL Server Database Engine task that has a severity level of 20 or higher and terminates the session. If the severity level of the error that occurred is 20 or higher, and the database connection is not interrupted, TRY ... CATCH will handle the error.
A message that needs attention, such as a client interrupt request or a client connection outage.
When the system administrator uses the KILL statement to terminate the session.
BEGINTRY--Generate a Divide-by-zero error.SELECT1/0; ENDTRY BEGINCatchSELECT Error_number ()As errornumber, error_severity () as errorseverity, error_state () as errorstate, error_procedure () as errorprocedure, error_line () as errorline, error_message () Span class= "Apple-converted-space" > as errormessage; End catch; go
UseAdventureWorks; GO BEGINTRANSACTION;
BEGINTRY--Generate a constraint violation error.DELETEFromProduction.ProductWHEREProductID=980; ENDTRY BEGINCatchSELECTError_number ()AsErrorNumber, Error_severity ()AsErrorSeverity, Error_state ()AsErrorState, Error_procedure ()AsErrorprocedure, Error_line ()As errorline, error_message () Span class= "Apple-converted-space" > as errormessage;
if @@ Trancount > 0 rollback transaction; End catch;
If @ @TRANCOUNT > 0 COMMIT transaction; GO
(GO) SQL Server2005 exception handling mechanism (Begin try begin Catch)