Thursday, February 25, 2010

SQL Server Error Handling

SQL Server Error Handling :

/*
Error handling in SQL Server breaks down into two very distinct
situations: you're handling errors because you're in SQL Server 2005
or you're not handling errors because you're in SQL Server 2000.
What's worse, not all errors in SQL Server, either version, can be
handled. I'll specify where these types of errors come up in each
version.

The different types of error handling will be addressed in two
different sections. 'll be using two different databases for the
scripts as well, [pubs] for SQL Server 2000 and [AdventureWorks]
for SQL Server 2005.

I've broken down the scripts and descriptions into sections. Here is
a Table of Contents to allow you to quickly move to the piece of code
you're interested in. Each piece of code will lead with the server
version on which it is being run. In this way you can find the section
and the code you want quickly and easily.
As always, the intent is that you load this workbench into Query Analyser
or Management Studio and try it out for yourself! The workbench script
is available from the CODE DOWNLOAD link above.

SQL Server 2005 - GENERATING AN ERROR */
---------------------------------------
USE AdventureWorks;
GO
UPDATE HumanResources.Employee
SET MaritalStatus = 'H'
WHERE EmployeeID = 100;

/* This generates a familiar error:
Msg 547, Level 16, State 0, Line 1
The UPDATE statement conflicted with the CHECK constraint
"CK_Employee_MaritalStatus".
The conflict occurred in database "AdventureWorks",
table "HumanResources.Employee", column 'MaritalStatus'.
The statement has been terminated.

No comments:

Post a Comment