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.

Chapter 12: Stored Procedures<br />

382<br />

checking works when it works, and how it doesn’t when it doesn’t (in particular, when inline does not<br />

work, but TRY/CATCH would).<br />

Let’s start with the referential integrity example we did earlier in this chapter:<br />

USE AdventureWorks<strong>2008</strong>;<br />

GO<br />

INSERT INTO Person.BusinessEntityContact<br />

(BusinessEntityID<br />

,PersonID<br />

,ContactTypeID)<br />

VALUES(0,0,1);<br />

You may recall this got us a simple 547 error. This is one of those that are trappable. We could trap this in<br />

a simple script, but let’s do it as a sproc since procedural stuff is supposedly what we’re working on<br />

here.<br />

USE AdventureWorks<strong>2008</strong><br />

GO<br />

CREATE PROC spInsertValidatedBusinessEntityContact<br />

@BusinessEntityID int,<br />

@PersonID int,<br />

@ContactTypeID int<br />

AS<br />

BEGIN<br />

END<br />

DECLARE @Error int;<br />

INSERT INTO Person.BusinessEntityContact<br />

(BusinessEntityID<br />

,PersonID<br />

,ContactTypeID)<br />

VALUES<br />

(@BusinessEntityID, @PersonID, @ContactTypeID);<br />

SET @Error = @@ERROR;<br />

IF @Error = 0<br />

PRINT ‘New Record Inserted’;<br />

ELSE<br />

BEGIN<br />

IF @Error = 547 -- Foreign Key violation. Tell them about it.<br />

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

ELSE -- something unknown<br />

PRINT ‘Unknown error occurred. Please contact your system admin’;<br />

END<br />

Now try executing this with values that work:<br />

EXEC spInsertValidatedBusinessEntityContact 1, 1, 11;

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

Saved successfully!

Ooh no, something went wrong!