In this post I will write a function that lists fibonacci series. It gets a parameter for max number then writes fibonacci series to that number.
First, we must create the function, the function’s code is below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
CREATE FUNCTION fn_Fibonacci(@max int) RETURNS @numbers TABLE(number int) AS BEGIN Declare @n1 int = 0,@n2 int =1,@i int=0,@temp int Insert Into @numbers Values(@n1),(@n2) WHILE (@i<=@max-2) BEGIN Insert Into @numbers Values(@n2+@n1) set @temp = @n2 Set @n2 = @n2 + @n1 Set @n1 = @temp Set @i += 1 END RETURN END |
If you get succesful message then you can execute the code below
Example-1
1 |
Select * from dbo.fn_Fibonacci(5) |
The Result Of Code
Example-2
1 |
Select * from dbo.fn_Fibonacci(15) |
The Result Of Code
Solution 2 For Fibonacci Sequence Function in Sql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Create FUNCTION fn_Fibonacci2(@count int) RETURNS @numbers TABLE(number int) AS BEGIN Declare @n int,@i int=0 Insert Into @numbers Values(0),(1) WHILE (@i<@count) BEGIN Select @n = sum(number) from (Select top 2 number from @numbers order by number desc) as T Insert Into @numbers Values(@n) Select @i = count(*) from @numbers END RETURN END |
If you get succesful message then you can execute the code below
Example-1
1 |
Select * from dbo.fn_Fibonacci2(5) |
The Result Of Code
Example-2
1 |
Select * from dbo.fn_Fibonacci2(15) |
The Result Of Code
TO SEE OTHER SQL MULTİSTATEMENT TABLE VALUED FUNCTİON EXAMPLES CLİCK