The use of the try catch of MSSQL is a popular explanation

Source: Internet
Author: User
Tags error handling sql 2008 mssql try catch

1.try Catch Personal understanding

A try catch is a block of statements that SQL uses for error handling, and when we write SQL statements (usually when we write more complex stored procedures), using try catch appropriately captures the error information of the SQL code runtime so that we can

It is easier to deal with the problems we encounter without having to judge them everywhere.

For example, in our process scripts, we often have to divide calculations such as this code declare @i int=0, @j =-Select @j/@i

If one day we want to write a very complex formula, often through the variable subtraction we have to add a judgment every time, and with a try catch, we do not have to add these judgments, direct capture can

3.try catch is used as follows, reader friends can do their own to SQL 2008 or 2005 Query Analyzer execution (pro-test error)

Create procUp_testcatch1 (@iStatus intOutput@StatusText varchar( +) out) as   begin  Select @iStatus=0,@StatusText='Successful Execution'    beginTrybegin Tran              SelectStatus of implementation='no mistake here will be performed'         Commit Tran    EndTrybeginCatchrollback Tran    EndCatchEndCreate procUP_TESTCATCH2 (@iStatus intOutput@StatusText varchar( +) out) as   begin  Declare @i int =0Select @iStatus=0,@StatusText='Successful Execution'    beginTrybegin Tran              Select @i=1/0 --Error here            Select 'skipping is not performed here when an error occurs'         Commit Tran    EndTrybeginCatch/*capture when an error occurs*/            SelectStatus of implementation='When an error occurs, it is executed here'        rollback Tran    EndCatchEndDeclare  @iStatus int,@StatusText varchar( +) execUp_testcatch1@iStatusOut,@StatusText outexecUp_testcatch2@iStatusOut,@StatusTextOut

The use of the try catch of MSSQL is a popular explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.