SQL Functions - factorial

前端 未结 12 1477
傲寒
傲寒 2020-11-30 14:55

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

12条回答
  •  爱一瞬间的悲伤
    2020-11-30 15:26

    I know I'm a little late here, but it's worth noting that the recursive way that Martin posted does not work for 0.

    This will (forgive me, I was having issues posting the code):


    declare @target int=3;
    
    WITH N AS
    (SELECT 1 AS i, 
            1 AS f
     UNION ALL
     SELECT i+1,
            f*(i+1)
     FROM N
     WHERE  i < @target),
    N0 AS
    (SELECT f FROM N WHERE i=@target UNION SELECT 0)
    SELECT MAX(f) FROM N0
    

    And for the way, way faster version:

    declare @target int=5;
    
    WITH N AS
    (SELECT 1 AS i, 
            1 AS f
     UNION ALL
     SELECT i+1,
            f*(i+1)
     FROM N
     WHERE i < @target),
    N0 AS
    (SELECT f FROM N WHERE i=@target UNION SELECT f=CASE WHEN @target=0 THEN 0 END)
    SELECT f FROM N0
    WHERE f>=0
    

    This is much faster because I lose the MAX() function which, just like top 1, causes a DISTINCT sort.

提交回复
热议问题