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.

You can test the arithmetic overflow easily by putting any large number in — anything bigger than<br />

about 13 will work for this example.<br />

Testing the 32-level recursion limit takes a little bit more modification to our sproc. This time, we’ll<br />

determine the triangular of the number. This is very similar to finding the factorial, except that we use<br />

addition rather than multiplication. Therefore, 5 triangular is just 15 (5+4+3+2+1). Let’s create a new<br />

sproc to test this one out — it will look just like the factorial sproc with only a few small changes:<br />

CREATE PROC spTriangular<br />

@ValueIn int,<br />

@ValueOut int OUTPUT<br />

AS<br />

DECLARE @InWorking int;<br />

DECLARE @OutWorking int;<br />

IF @ValueIn != 1<br />

BEGIN<br />

SELECT @InWorking = @ValueIn - 1;<br />

END<br />

ELSE<br />

BEGIN<br />

END<br />

RETURN;<br />

GO<br />

EXEC spTriangular @InWorking, @OutWorking OUTPUT;<br />

SELECT @ValueOut = @ValueIn + @OutWorking;<br />

SELECT @ValueOut = 1;<br />

As you can see, there weren’t that many changes to be made. Similarly, we only need to change our<br />

sproc call and the PRINT text for our test script:<br />

DECLARE @WorkingOut int;<br />

DECLARE @WorkingIn int;<br />

SELECT @WorkingIn = 5;<br />

EXEC spTriangular @WorkingIn, @WorkingOut OUTPUT;<br />

PRINT CAST(@WorkingIn AS varchar) + ‘ Triangular is ‘ + CAST(@WorkingOut AS<br />

varchar);<br />

Running this with an @ValueIn of 5 gets our expected 15:<br />

5 Triangular is 15<br />

Chapter 12: Stored Procedures<br />

However, if you try to run it with an @ValueIn of more than 32, you get an error:<br />

Msg 217, Level 16, State 1, Procedure spTriangular, Line 10<br />

Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).<br />

401

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

Saved successfully!

Ooh no, something went wrong!