Procedure for Recursive Calculation of Factorial Calculation in SQL Server

Hello everyone,

In this section, I will make an example of a procedure that recursively calculates factorial in SQL Server.

First, let’s talk about what factorial is.

The product of numbers starting from 1 up to a certain counting number is called the factorial of that number.

For example, the factorial of 5 (denoted by 5!): 120 = 5 * 4 * 3 * 2 * 1.

What is recursive?

If a structure has the ability to refer to itself, such structures are called recursive structures.

Now let’s move on to the code example.

CREATE PROCEDURE CalculateFactorial
(
    @Number INTEGER,
    @Result INTEGER OUTPUT
)
AS
DECLARE @Input INTEGER;
DECLARE @Output INTEGER;
IF @Number != 1
BEGIN
    SELECT @Input = @Number - 1;
    EXEC FaktoriyelHesapla @Input, @Output OUTPUT;
    SELECT @Result = @Number * @Output;
END;
ELSE
BEGIN
    SELECT @Result = 1;
END;
RETURN; 

--Çalıştırılması 

DECLARE @Result INTEGER;
EXEC CalculateFactorial @Number = 5,              -- integer 
                       @Result = @Result OUTPUT; -- integer 
PRINT @Result;

When you create and run the above procedure, you will see a result similar to the one below.

Procedure for Recursive Calculation of Factorial Calculation in SQL Server

As can be seen, we have calculated the factorial recursively.

Good luck to everyone in business and life.

162 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!