简体   繁体   中英

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;    

You can use recursive query to generate numbers.

with cte (ct) as (
  select 1 as ct from dual
  union all
  select ct + 1 from cte
     where ct < 10
) select ct from cte

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM