In our School day teacher always taught us Fibonacci sequence in math.And in Our programming period We are creating so many time the Fibonacci series in Different language like Fibonacci C#,Fibonacci series in python ,Java,C Fibonacci ,C++ and many other language .I am here to write a T-SQL to generate the Fibonacci series. Fibonacci Table is created in below example.I hope you all aware about the Fibonacci Formula. Fibonacci formula is like the next number is the sum of previous two number. So apply this formula we get Fibonacci sequence.

I am using CTE (Common Tabular Expression) to do this.

SQL Recursive method is very good to get the desired output.

### Fibonacci Series Example

`;WITH Fibonacci (PrevNumber, N) AS`

`(`

` SELECT 0, 1`

` UNION ALL`

` SELECT N, PrevNumber + N`

` FROM Fibonacci`

` WHERE N < 100`

`)`

`SELECT PrevNumber as FibonacciSeries`

`FROM Fibonacci`

`OPTION (MAXRECURSION 0);`

### Explanation

I am using OPTION (MAXRECURSION 0) due to increase the recursion up to infinite time.Simple from the output its clear that series are in Fibonacci.You also generate it into single comma separated by using for xml path(''). So its all about the Fibonacci series in SQL Server. Hope you like this post.

## 0 comments:

## Post a comment