SQL Query to return N rows from dual

前端 未结 10 1840
盖世英雄少女心
盖世英雄少女心 2021-02-13 10:31

I want to write a SQL query which accepts a bind variable (say :NUM) and its output consists of one column & :NUM number of rows, each row having its row number. i.e. if we

10条回答
  •  失恋的感觉
    2021-02-13 11:17

    Another solution would require some PL/SQL to create a function to return a collection with the rows... Not as simple as the select level from dual connect by level <= :b1 approach, but it's useful in a few situations:

    1) Create a number table object type ( number_tbl, in this example ) :

    create or replace type number_tbl as table of number;
    

    2) Create a function that will receive the number of rows to be generated, and then return a number_tbl object with the results:

    create or replace function get_rows( i_num_rows number ) return number_tbl as
      t number_tbl := number_tbl();
    begin
      if i_num_rows < 1 then
        return null;
      end if;
    
      t.extend( i_num_rows );
    
      for i in 1..i_num_rows loop
        t(i) := i;
      end loop;
    
      return t;
    end get_rows;
    

    3) select from your function using the table( ... ) function to turn your number_tbl object into something selectable:

    select * from table( cast ( get_rows( :b1 ) as number_tbl ) );
    

提交回复
热议问题