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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Our insert happens correctly, so no error condition is detected (because there isn’t one).<br />

(1 row(s) affected)<br />

New Record Inserted<br />

Now, try something that should blow up:<br />

EXEC spInsertValidatedBusinessEntityContact 0, 1, 11;<br />

And you see not only the actual <strong>SQL</strong> <strong>Server</strong> message, but the message from our error trap (note that<br />

there is no way of squelching the <strong>SQL</strong> <strong>Server</strong> message).<br />

Msg 547, Level 16, State 0, Procedure spInsertValidatedBusinessEntityContact, Line<br />

11<br />

The INSERT statement conflicted with the FOREIGN KEY constraint<br />

“FK_BusinessEntityContact_Person_PersonID”. The conflict occurred in database<br />

“AdventureWorks<strong>2008</strong>”, table “Person.Person”, column ‘BusinessEntityID’.<br />

The statement has been terminated.<br />

At least one provided parameter was not found. Correct and retry<br />

As you can see, we were able to detect our error without a TRY/CATCH block.<br />

Now, let’s move on to an example of why TRY/CATCH is better — a situation where a TRY/CATCH works<br />

fine, but where inline error checking fails. To show this one off, all we need to do is use our example for<br />

TRY/CATCH that we used in the scripting chapter. It looked like this:<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();<br />

Chapter 12: Stored Procedures<br />

IF @ErrorNo = 2714 -- Object exists error, we knew this might happen<br />

PRINT ‘WARNING: Skipping CREATE as table already exists’;<br />

ELSE -- hmm, we don’t recognize it, so report it and bail<br />

RAISERROR(@Message, 16, 1 );<br />

END CATCH<br />

383

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

Saved successfully!

Ooh no, something went wrong!