What is the Fibonacci series: The first number of this series is 0 and the second number is 1. The other numbers in this series are found by the sum of the two preceding numbers. For example, the 3rd number in the series is 1, which is the sum of 0 and 1. The 4th number in the series is the sum of 1 and 1 is 2. The 5th issue of the series is; It is equal to 3, which is the sum of the number 2, which is the 4th number in the series, and the number 1, which is the 3rd number in the series. The series continues like this.
We will write a procedure that finds this series. The number of the serial number that is desired to be displayed as a parameter will be entered. The procedure will show us as many results as requested.
The code of the procedure is as follows. First we need to run this code. If we ran it without an error message, we can now use our procedure.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
DELIMITER $$ CREATE PROCEDURE `Sp_Fibonacci2`(IN `c` INT) BEGIN Set @n1 := 0, @n2 := 1, @i:=0,@temp:=0; CREATE TEMPORARY TABLE Numbers (Num int); Insert Into Numbers VALUES(@n1),(@n2); WHILE (@i< c) Do Set @temp = @n2; Set @n2 = @n2 + @n1; Set @n1 = @temp; Insert Into Numbers VALUES(@n2); SET @i := @i + 1; END WHILE; SELECT Num FROM numbers; DROP TABLE numbers; END$$ DELIMITER ; |
When you run the code above you will get succesfull message. After you can run the codes below
Example-1
1 |
Call Sp_Fibonacci (5); |
Result
Example-2
1 |
Call Sp_Fibonacci (15); |
Result
MySql 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 15 16 17 |
DELIMITER $$ CREATE PROCEDURE `Sp_Fibonacci2`( IN `c` INT ) BEGIN Set @n := 0, @i:=0; CREATE TEMPORARY TABLE Numbers (Num int); Insert Into Numbers VALUES(0),(1); WHILE (@i< c) DO SET @n = (SELECT sum(Num) from (Select Num from Numbers order by Num DESC LIMIT 2) AS T); Insert Into Numbers VALUES(@n); Set @i = (Select count(*) from Numbers); END WHILE; SELECT Num FROM numbers; DROP TABLE numbers; END$$ DELIMITER ; |
Example-1
1 |
Call Sp_Fibonacci (5); |
Result
Example-2
1 |
Call Sp_Fibonacci (15); |
Result