17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11: Writing Scripts and Batches<br />

362<br />

exit the TRY block immediately and begin with the first line in your CATCH block. Since there are more<br />

possible error levels than just 11–19, take a look at what we have there:<br />

Error Level Nature<br />

1–10 Informational only. This would include things like context changes such as settings<br />

being adjusted or NULL values found while calculating aggregates. These<br />

will not trigger a CATCH block, so if you need to test for this level of error, you’ll<br />

need to do so manually by checking @@ERROR.<br />

11–19 Relatively severe errors, but ones that can be handled by your code (foreign key<br />

violations, as an example). Some of these can be severe enough that you are<br />

unlikely to want to continue processing (such as a memory exceeded error), but<br />

at least you can trap them and exit gracefully.<br />

20–25 Very severe. These are generally system-level errors. Your server-side code will<br />

never know this kind of error happened, as the script and connection will be terminated<br />

immediately.<br />

Keep these in mind — if you need to handle errors outside the 11–19 level range, then you’ll need to<br />

make other plans.<br />

Now, to test this out, we’ll make some alterations to our CREATE script that we built back when we were<br />

looking at IF...ELSE statements. You may recall that part of the reason for our original test to see<br />

whether the table already existed was to avoid creating an error condition that might have caused our<br />

script to fail. That kind of test is the way things have been done historically (and there really wasn’t<br />

much in the way of other options). With the advent of TRY/CATCH blocks, we could just try the CREATE<br />

and then handle the error if one were given:<br />

BEGIN TRY<br />

-- Try and create our table<br />

CREATE TABLE OurIFTest(<br />

Col1 int PRIMARY KEY<br />

);<br />

END TRY<br />

BEGIN CATCH<br />

-- Uh oh, something went wrong, see if it’s something<br />

-- we know what to do with<br />

DECLARE @ErrorNo int,<br />

@Severity tinyint,<br />

@State smallint,<br />

@LineNo int,<br />

@Message nvarchar(4000);<br />

SELECT<br />

@ErrorNo = ERROR_NUMBER(),<br />

@Severity = ERROR_SEVERITY(),<br />

@State = ERROR_STATE(),<br />

@LineNo = ERROR_LINE (),<br />

@Message = ERROR_MESSAGE();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!