Jason Jason - 3 months ago 17
SQL Question

SQL Functions - factorial

I am a beginner in SQL Functions.
What is the best way to create a function for factorial in SQL Server- Say 10!

Answer

Here is a recursive solution:

CREATE FUNCTION dbo.Factorial ( @iNumber int )
RETURNS INT
AS
BEGIN
DECLARE @i  int

    IF @iNumber <= 1
        SET @i = 1
    ELSE
        SET @i = @iNumber * dbo.Factorial( @iNumber - 1 )
RETURN (@i)
END
Comments