Talk:Fibonacci numbers (T-SQL)

From LiteratePrograms

Jump to: navigation, search

Well, if you allow the MS function syntax for T-SQL, then you could write it as:

CREATE FUNCTION fib(@n INT) RETURNS INT
AS
BEGIN
   RETURN
       CASE @n
          WHEN 0 THEN 0
          WHEN 1 THEN 1
          ELSE dbo.fib(@n - 1) + dbo.fib(@n - 2)
       END
END
GO

SELECT dbo.fib(10)
GO

That will bounce into the depth limit of 32 on the nested recursion (lower for older versions). To get around that, you could reformulate the iteration as a function along the lines of:

CREATE FUNCTION fib_iter(@n INT) RETURNS INT
AS
BEGIN
   IF (@n = 0) RETURN 0
   IF (@n = 1) RETURN 1

   DECLARE @a INT
   DECLARE @b INT
   DECLARE @fib INT

   SET @a = 0
   SET @b = 1
   SET @fib = 0

   WHILE @n > 1
      BEGIN
         SET @n = @n - 1
         SET @fib = @a + @b
         SET @a = @b
         SET @b = @fib
      END

   RETURN @fib
END
GO

SELECT dbo.fib_iter(46)
GO
Personal tools