Search code examples
mysqlsqldatabaseoracleoracle10g

How to return 1,2,3.... to N in a separate row from function in ORACLE?


I am new to oracle.I want to send a number to a function and want to print upto the value of n.1,2...n

suppose if i send n=5 then my output will be like,

-------
i     |
-------
 1    |
  2   |
  3   |
  4   |
   5  |

Suppose if I pass n=10 then,

-------
i     |
-------
 1    |
  2   |
  3   |
  4   |
   5  |
  6   |
   7  |
   8  |
   9  |
  10  | 

When I pass,n=10 then my output is coming as ,

-------
i     |
-------
 10  |    

I tried:

CREATE OR REPLACE FUNCTION OT.NUMBER_GEN(
data1 NUMBER
)
return VARCHAR2
IS
V_ALL_NUMBER VARCHAR2 
BEGIN
FOR REC IN data1
Loop
V_ALL_NUMBER := REC;
END LOOP;
RETURN V_ALL_NUMBER;
END OT.NUMBER_GEN;    

Solution

  • Create a custom nested table of numbers and have the function return that type:

    create or replace type number_nt is table of number;
    
    create or replace function number_gen(data1 number) return number_nt is
        v_numbers number_nt := number_nt();
    begin
        for i in 1 .. data1 loop
            v_numbers.extend;
            v_numbers(v_numbers.count) := i;
        end loop;
        return v_numbers;
    end;
    /
    
    select * from table(number_gen(5));
    

    However, the easiest way to create a list of number would be this SQL statement:

    select level i from dual connect by level <= 5;