Search code examples
oracleplsqlstored-functions

Function compiled but no output in oracle


I'm trying to write a stored function that takes an integer N as input and returns the sum of all numbers divisible by 3 or by 5 and less than or equal to N.

SET SERVEROUTPUT ON;

CREATE OR REPLACE FUNCTION somme_mod(N in INTEGER) RETURN INTEGER
as
somme INTEGER:= 0;
i INTEGER:= 0;


BEGIN
    WHILE i <= N LOOP
        IF i MOD 3 = 0 OR i MOD 5 = 0 THEN
            somme := somme + i;
        END IF;
            i := i+1;

    END LOOP;
    RETURN (somme);
    
    DBMS_OUTPUT.PUT_LINE(somme_mod(5));

END;
/

I'm getting this:

Function SOMME_MOD compiled

This version has worked for me

SET SERVEROUTPUT ON;
DECLARE
FUNCTION somme_mod(N in INTEGER) 
RETURN INTEGER
as
somme INTEGER:= 0;
i INTEGER:= 0;

BEGIN
    WHILE i <= N LOOP
        IF i MOD 3 = 0 OR i MOD 5 = 0 THEN
            somme := somme + i;
        END IF;
        
        i := i+1;
    END LOOP;
    RETURN (somme);
END;
BEGIN
    DBMS_OUTPUT.PUT_LINE(somme_mod(19));
END;
/

Solution

  • You only compiled the procedure, that's what the CREATE OR REPLACE does - hence that feedback from the database.

    Now if you want to actually execute your function, you need to invoke it.

    The easiest way to do that is with SQL.

    select somme_mod(1) from dual;
    

    No comment on your PL/SQL but be careful you don't get into a LOOP that NEVER ends...and then never makes it to the RETURN.