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 12: Stored Procedures<br />

374<br />

[ErrorProcedure],<br />

[ErrorLine],<br />

[ErrorMessage]<br />

)<br />

VALUES<br />

(<br />

CONVERT(sysname, CURRENT_USER),<br />

ERROR_NUMBER(),<br />

ERROR_SEVERITY(),<br />

ERROR_STATE(),<br />

ERROR_PROCEDURE(),<br />

ERROR_LINE(),<br />

ERROR_MESSAGE()<br />

);<br />

-- Pass back the ErrorLogID of the row inserted<br />

SET @ErrorLogID = @@IDENTITY;<br />

END TRY<br />

BEGIN CATCH<br />

PRINT ‘An error occurred in stored procedure uspLogError: ‘;<br />

EXECUTE [dbo].[uspPrintError];<br />

RETURN -1;<br />

END CATCH<br />

END;<br />

Note the sections that I’ve highlighted here — these are the core to our output parameter. The first declares<br />

the parameter as being an output parameter. The second makes the insert that utilizes the identity<br />

value, and, finally, the SET statement captures the identity value. When the procedure exists, the value in<br />

@ErrorLogID is passed to the calling script.<br />

Let’s utilize our TRY/CATCH example from the tail end of the last chapter, but this time we’ll make the<br />

call to uspLogError:<br />

USE AdventureWorks<strong>2008</strong>;<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 @MyOutputParameter int;<br />

IF ERROR_NUMBER() = 2714 -- Object exists error, we knew this might happen<br />

BEGIN<br />

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

EXEC dbo.uspLogError @ErrorLogID = @MyOutputParameter OUTPUT;<br />

PRINT ‘A error was logged. The Log ID for our error was ‘<br />

+ CAST(@MyOutputParameter AS varchar);<br />

END

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

Saved successfully!

Ooh no, something went wrong!