阶乘函数错误-超过最大存储过程,函数,触发器或视图嵌套级别

时间:2018-12-17 12:31:28

标签: sql-server tsql probability factorial

我正在尝试运行以下阶乘函数,但出现以下错误。
已超过最大存储过程,函数,触发器或视图嵌套级别(限制32)。

这可以解决吗?

The binomial formula given that
x = total number of “successes” (pass or fail, heads or tails etc.) -- 0.025
P = probability of a success on an individual trial --Rate  0.000729
n = number of trials   -- Denominator 13725
q= 1 – p –- is as below:

    DECLARE @n float(53), @x float(53), @p decimal(10, 10), @q decimal(10,10)
    DECLARE @p0 decimal(10,10), @p1 decimal(10,10), @p2 decimal(10,10), @n1 float(53), @n2 float(53), @n3 float(53)
    SELECT @n =13725 , @x = 0.025 , @p = 0.000729,@q=1-@p 
    SELECT @x = 0.025
    SELECT @n1 = dbo.factorial(@n) 
    SELECT @n2 = dbo.factorial(@n-@x)
    SELECT @n3 = 1
    SELECT @p1 = ( @n1/(@n2 * @n3))*power(@p, @x)*power(@q,@n-@x)
    select @p1 as 'Probability of 0 people getting lung illness'

---factorial function
    create function dbo.factorial(@num1 float(53))
    returns float(53)
    as
    begin
    declare @factno bigint;
     
    if  (@num1=1)  set @factno=1;
    else 
     
    set @factno= @num1*dbo.factorial(@num1-1);
     return @factno;

    end
    go

1 个答案:

答案 0 :(得分:0)

递归计算并不是SQL Server(以及其他任何数据库)的亮点。最好的解决方案是将其移出数据库并在您的应用程序中对其进行计算。但是,如果您绝对必须在数据库中执行此操作,请使用一种迭代方法而不是递归方法,例如:

create function dbo.factorial(@num1 float(53))
returns float(53)
as
begin
    declare @factno bigint;

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

    return @factno;
end