Server
The newly added try catch in SQL Server 2005 can easily catch exceptions, and today I probably learned to look at the following points, summed up the following
Basic usage Begin TRY
{sql_statement |
Statement_block}
End TRY
BEGIN CATCH
{sql_statement |
Statement_block}
End CATCH
is similar to common language exception handling, but it should be noted that SQL Server captures only those exceptions that are not serious, such as exceptions such as a database that cannot be connected, an example that cannot be captured: the BEGIN TRY
DECLARE @x INT
--Divide by zero to generate Error
SET @x = 1/0
PRINT ' Command after error in TRY block '
End TRY
BEGIN CATCH
PRINT ' Error detected '
End CATCH
PRINT ' Command after Try/catch blocks '
Another try catch can nest the begin TRY
Delete from grandparent where Name = ' John Smith '
print ' grandparent deleted successfully '
End Try
Begin Catch
Print ' Error deleting grandparent record '
Begin Try
Delete from Parent where Grandparentid =
(select distinct ID from grandparent where Name = ' John Smith ')
Print ' Parent Deleted successfully '
End Try
Begin Catch
print ' Error deleting Parent '
Begin Try
Delete from child where ParentID =
(select distinct ID from Parent where Grandparentid =
(select distinct ID from grandparent where Name = ' John Smith '))
print ' Child Deleted successfully '
End Try
Begin Catch
Print ' Error deleting child '
End Catch
End Catch
End Catch
In addition, SQL SERVER 2005 in the exception mechanism, provided the error class method to facilitate debugging, now excerpt as follows, relatively simple, do not explain Error_number (): Returns A number associated with the error. Error_severity (): Returns the SEVERITY of the error. Error_state (): Returns the Error state number associated with the error. Error_procedure (): Returns The name of the stored PROCEDURE or trigger in which the error occurred. Error_line (): Returns the line number inside the failing routine that caused the error. Error_message (): Returns The complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times. The last example is as follows: The method of using the error class to begin TRY
DECLARE @x INT
--Divide by zero to generate Error
SET @x = 1/0
PRINT ' Command after error in TRY block '
End TRY
BEGIN CATCH
PRINT ' Error detected '
SELECT error_number () Ernumber,
Error_severity () error_severity,
Error_state () Error_state,
Error_procedure () Error_procedure,
Error_line () Error_line,
Error_message () error_message
End CATCH
PRINT ' Command after Try/catch blocks '
Final output error detected
Err_num Err_sev err_state err_proc err_line err_msg
------- ------- --------- -------------------- --------- --------------------------------
8134 1 NULL 4 Divide by zero error encountered.