SQL Functions - factorial

前端 未结 12 1458
傲寒
傲寒 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:29

    -- Iterative method. -- Why Iterative? It is simpler and faster. -- For @N from 0 to 20 this gives an exact result. -- 21 will give an overflow.

    DECLARE @N Bigint = 20
    DECLARE @F Bigint = 1
    WHILE @N > 0 BEGIN
      SET @F = @f*@n
      SET @N = @N-1
    END
    SELECT @F AS FACTORIAL
    

    -- Change the datatype to float and you can get the factorial up to 170. -- 171 will result in an overflow. -- Remark the result will only be accurate over a limited number of positions.

    DECLARE @N FLOAT = 170
    DECLARE @F FLOAT = 1
    WHILE @N > 0 BEGIN
      SET @F = @f*@n
      SET @N = @N-1
    END
    SELECT @F AS FACTORIAL
    

    -- Ben

提交回复
热议问题