In this post we will write sql stored procedure to list fibonacci series. It gets a number parameter to be listed sequence. The procedure’s code is below.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | Create Procedure sp_Fibonacci(@max int) AS BEGIN Declare @numbers table(number int) 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 Select * from @numbers END |

When you run the code above you will get succesfull message. After you can run the codes below

**Example-1**

1 | Exec sp_Fibonacci 5 |

**Result**

**Example-2**

1 | Exec sp_Fibonacci 15 |

**Result**

## Sql Fibonacci Sequence With Stored Procedure Solution 2

The deference in this solution, I used the query in the aggregation process. In solution 1, I used two integer variable instead.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Create Procedure sp_Fibonacci2(@count int) AS BEGIN Declare @numbers TABLE(number int)//Defining table variable Declare @n int,@i int=0 // Define variable for add 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 Select * from @numbers END |

**Example-1**

1 | Exec sp_Fibonacci2 5 |

**Result**

**Example-2**

1 | Exec sp_Fibonacci2 15 |

**Result**