Microsoft SQL Server 2012 Bible
by Adam Jorgensen, Jorge Segarra, Patrick LeBlanc, Jose Chinchilla, Aaron Nelson
Error Handling
If you've never encountered an error in T-SQL, you're better than most people. For everyone else, error handling is a critical and often overlooked component of T-SQL programming.
Of course, all robust programming languages provide some method for trapping, logging, and handling errors. In this area, T-SQL has a sad history, but it's made significant progress over the last couple of releases.
There are two distinctly different ways to code error handling with SQL Server:
- Legacy error handling is how it's been done since the beginning of SQL Server, using @@error to see the error status of the previous SQL statement.
- Try/catch was introduced in SQL Server 2005, bringing SQL Server into the 21st century. I highly recommend taking this approach.
Legacy Error Handling
Historically, T-SQL error handling has been tedious at best. I'd prefer to not even include this legacy method of handling errors, but you'll see it in old code, so it must be covered.
The basic error information system functions, such as @@error and @@rowcount, contain the status for the previous T-SQL command in the code. This means that the legacy method of error handling must examine T-SQL's system functions ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access