一連の要因(3、5、7として表示)は奇数のセットとして増加すると想定しています。このソリューションでは、共通テーブル式を使用しています。つまり、SQLServer2005以降を使用する必要があります。
Declare @x float;
Declare @y float;
-- this is the first factor evaluated
-- e.g., in the example, 3 is the first factor
-- values less that one effectively set the min
-- to one.
Declare @FactorMin int;
-- this is the maximum number of iterations
-- i.e., 3, 5, 7,
Declare @FactorMax int
Set @x = 20;
Set @y = 20;
Set @FactorMin = 3;
Set @FactorMax = 15;
With Numbers As
(
Select 1 As Value
Union All
Select Value + 1
From Numbers
Where Value < @FactorMax
)
, OddNumbers As
(
Select Value
, Row_Number() Over( Order By Value ) As Position
From Numbers
Where Value % 2 = 1
And Value Between @FactorMin And @FactorMax
)
, Factorials As
(
Select O.Value, O.Position
, Exp(Sum(Log(N1.Value))) As Factorial
, Case When O.Position % 2 = 1 Then -1 * @y Else @x End As XOrY
From OddNumbers As O
Cross Join Numbers As N1
Where N1.Value <= O.Value
Group By O.Value, O.Position
)
Select Sum( Z.Value )
From (
Select @x As Value
Union All
Select Power(XOrY, Value) / Factorial
From Factorials
) As Z
Option (MaxRecursion 0);