Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 915
Jason Avatar asked Aug 17 '10 16:08

Jason


2 Answers

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
like image 194
Abe Miessler Avatar answered Oct 02 '22 18:10

Abe Miessler


A non recursive way

;With Nums As
(
select ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS RN
FROM sys.objects
)
SELECT  POWER(10.0, SUM(LOG10(RN)))
FROM Nums
WHERE RN <= 10

And a recursive way

declare @target int
set @target=10;

WITH N AS
     (SELECT 1 AS i,
           1 AS f

     UNION ALL

     SELECT i+1,
            f*(i+1)
     FROM   N
     WHERE  i < @target
     )
SELECT f FROM N
WHERE i=@target
like image 24
Martin Smith Avatar answered Oct 02 '22 17:10

Martin Smith