Implementing the fibonacci() User-Defined Function with Recursion : Recursive function « Procedure Function « SQL Server / T-SQL Tutorial






4> CREATE FUNCTION dbo.fibonacci(
5>   @n AS int
6> )
7> RETURNS int
8> AS
9> BEGIN
10>   RETURN CASE
11>             WHEN @n > 1 THEN @n + dbo.fibonacci(@n - 1) --recursive invocation
12>             WHEN @n IN (0, 1) THEN @n
13>             ELSE NULL
14>           END
15> END
16> GO
1>
2> --Invoking the Recursive fibonacci() User-Defined Function
3>
4> SELECT dbo.fibonacci(2) -- succeeds
5> GO

-----------
          3

(1 rows affected)
1>
2> drop function dbo.fibonacci
3> GO








21.3.Recursive function
21.3.1.Recursively call itself
21.3.2.iterative solution does not have the restriction 32 nesting levels
21.3.3.Implementing the fibonacci() User-Defined Function with Recursion
21.3.4.Implementing the fibonacci2() User-Defined Function with a Loop
21.3.5.Nesting Stored Procedures