Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate Fibonacci Series [closed]

Tags:

sql

sql-server

How to Generate Fibonacci series in sql !

I need to generate Fibonacci series 0 1 1 2 3 5 8 13 21 ... N

I did this easily using C-code I need to do this using Sql !


1 Answers

Try This Simple Query:

1) For Result In Row-by-Row (Single Column, Multiple Rows)

WITH Fibonacci (PrevN, N) AS
(
     SELECT 0, 1
     UNION ALL
     SELECT N, PrevN + N
     FROM Fibonacci
     WHERE N < 1000000000
)
SELECT PrevN as Fibo
     FROM Fibonacci
     OPTION (MAXRECURSION 0);

Output 1:

enter image description here

2) For Result in Only One Row (Comma sepreted, in Single Cell)

WITH Fibonacci (PrevN, N) AS
(
 SELECT 0, 1
    UNION ALL
    SELECT N, PrevN + N
    FROM Fibonacci
    WHERE N < 1000000000
)
SELECT Substring(
    (SELECT cast(', ' as varchar(max)) + cast(PrevN as varchar(max)
);
FROM Fibonacci
FOR XML PATH('')),3,10000000) AS list

Output 2: enter image description here

like image 147
124 Avatar answered Jan 25 '26 07:01

124



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!