Recursive Stored Procedure to generate Factorials

Bandi
Posted by Bandi under Sql Server category on | Points: 40 | Views : 318
CREATE PROCEDURE spFactorial
@ValueIn int,
@ValueOut int OUTPUT
AS
DECLARE @InWorking int
DECLARE @OutWorking int
IF @ValueIn > 1
BEGIN
SELECT @InWorking = @ValueIn - 1

EXEC spFactorial @InWorking, @Outworking OUTPUT

SELECT @ValueOut = @ValueIn * @OutWorking
END
ELSE
BEGIN
SELECT @ValueOut = 1
END
RETURN
GO

DECLARE @WorkingOut int
DECLARE @WorkingIn int
SELECT @WorkingIn = 4 -- input number
EXEC spFactorial @WorkingIn, @WorkingOut OUTPUT

PRINT CAST(@WorkingIn AS varchar) + ' factorial is ' + CAST(@WorkingOut AS varchar)

SELECT @WorkingIn = 5
EXEC spFactorial @WorkingIn, @WorkingOut OUTPUT

PRINT CAST(@WorkingIn AS varchar) + ' factorial is ' + CAST(@WorkingOut AS varchar)
GO

--clean up code
DROP PROC spFactorial;


Output:

4 factorial is 24
5 factorial is 120

Comments or Responses

Login to post response