1

My approach

DELIMITER $$
CREATE FUNCTION fibonacci(num INT)
RETURNS INT
DETERMINISTIC
BEGIN
    DECLARE fib1 INT DEFAULT 0;
    DECLARE fib2 INT DEFAULT 1;
    DECLARE fib3 INT DEFAULT 0;
    DECLARE str VARCHAR(255) DEFAULT '01';
    
    IF num = 1 THEN
        RETURN fib1;
    ELSEIF num = 2 THEN
        RETURN CONCAT(fib1, fib2);
    ELSE
        WHILE num > 2 DO
            SET fib3 = fib1 + fib2;
            SET fib1 = fib2;
            SET fib2 = fib3;
            SET num = num - 1;
            SET str = CONCAT(str, fib3);
        END WHILE;
        RETURN str;
    END IF;
END $$
DELIMITER ;

If I call above function using SELECT fibonacci(6); it returns 11235 without leading zero(0). How I can show leading zero also?

Shadow
  • 33,525
  • 10
  • 51
  • 64
  • PL/SQL is procedural extension to Oracle's SQL, while your code is **not** Oracle. I removed that tag, I suggest you fix the title. – Littlefoot Nov 03 '21 at 08:37
  • It is similar to pl/sql – Albert Einstein Nov 03 '21 at 08:39
  • 2
    Noway. The datatype of the function output is `RETURNS INT`, so leading zero will be removed even if you'd add it. Alter the output datatype to `VARCHAR(255)`. – Akina Nov 03 '21 at 08:45
  • I think @Akina nailed the answer: change the return value to varchar. – Shadow Nov 03 '21 at 08:48
  • *if I want to return INT then how can I display leading zero?* Do not mix "receive the output" and "show received output on the screen". – Akina Nov 03 '21 at 08:49

1 Answers1

0

i think it will help you

DELIMITER $$
CREATE FUNCTION fibonacci_number(n INT) RETURNS INT
DETERMINISTIC
BEGIN
    DECLARE f_0 INT default 0;
    DECLARE f_1 INT DEFAULT 1;
    DECLARE out_fib INT;
    DECLARE i INT;
    DECLARE f_2 INT;

    SET f_0 = 0;
    SET f_1 = 1;
    SET i = 1;

    WHILE (i<=n) DO
        SET f_2 = f_0 + f_1;
        SET f_0 = f_1;
        SET f_1 = f_2;
        SET i = i + 1;
    END WHILE;
    SET out_fib = f_0;
RETURN out_fib;
END $$
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 12 '21 at 17:15