· 9 years ago · Oct 22, 2016, 07:32 AM
1drop table if exists `test_fib`;
2
3create table `test_fib` (
4 `idx` bigint unsigned not null auto_increment,
5 `num` bigint unsigned not null,
6 primary key (`idx`));
7
8insert into `test_fib` (`num`) values (1);
9insert into `test_fib` (`num`) values (1);
10select * from `test_fib`;
11
12drop procedure if exists `sp_test_fib`;
13
14delimiter $$
15create procedure `sp_test_fib` (in `in_idx` bigint unsigned)
16begin
17 declare `max_idx` bigint unsigned default 0;
18 declare `out_num` bigint unsigned default 0;
19 declare `diff_idx` bigint unsigned default 0;
20 declare `next_max_num` bigint unsigned default 0;
21
22 select max(`idx`) into `max_idx` from `test_fib`;
23
24 if `max_idx` >= `in_idx` then
25 select `num` into `out_num` from `test_fib` where `idx` = `in_idx`;
26 else
27 set `diff_idx` = `in_idx` - `max_idx`;
28 while `diff_idx` > 0 do
29 set `next_max_num` =
30 (select `num` from `test_fib` where `idx` = (`max_idx` - 1)) +
31 (select `num` from `test_fib` where `idx` = `max_idx`);
32 insert into `test_fib` (`num`) values (`next_max_num`);
33 set `max_idx` = `max_idx` + 1;
34 set `diff_idx` = `diff_idx` - 1;
35 end while;
36 select max(`num`) into `out_num` from `test_fib`;
37 end if;
38
39 select `out_num`;
40end$$
41DELIMITER ;
42
43call `sp_test_fib`(50);
44call `sp_test_fib`(3);
45select * from `test_fib`;