SQL Query to return N rows from dual

前端 未结 10 1839
盖世英雄少女心
盖世英雄少女心 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:22

    You could use:

     WHERE ROWNUM <= :NUM
    

    ...but the table has to contain row equal or greater to the limit in the bind variable. This link demonstrates various row number generation techniques in Oracle.

    Using CONNECT BY, Oracle 10g+:

    SELECT LEVEL
      FROM DUAL
    CONNECT BY LEVEL <= :NUM
    

    Confirmed by monojohnny that the bind variable can be used. Attempts to run on Oracle 9i, though CONNECT BY syntax is supported results in an ORA-01436 error.

    The only thing I'm not 100% on is if the CONNECT BY will accept the limit from the bind variable.

    Reference:

    • Integer Series Generators - CONNECT BY LEVEL Method
    0 讨论(0)
  • 2021-02-13 11:24

    connect by is such a wonderful thing. It helps you generated multiple rows with a single set of data available in dual table. This can help you generate huge no of rows for your dummy data. For example

    insert into test select a.* from test1 a,(select * from dual connect by level <=100000) b;
    

    or you can do something like this

    Example 2 : You want to print square and cube of numbers from 1 to 10.

    SQL> select level "No", power(level,2) "Square", power(level,3) "Cube"  from dual     connect by level <= 10;
    
        No     Square       Cube
    ---------- ---------- ----------
         1          1          1
         2          4          8
         3          9         27
         4         16         64
         5         25        125
         6         36        216
         7         49        343
         8         64        512
         9         81        729
        10        100       1000
    

    Hence you can manipulate it in whatever form you want. This is how you can return multiple rows from dual table. References : http://www.oraclebin.com/2012/12/multipe-rows-from-dual-table.html

    0 讨论(0)
  • 2021-02-13 11:29

    Query without connect by

    WITH num(n) as(select 1 from dual union all
    select n+1 from num where n <= :num_limit)
    select * from num
    
    0 讨论(0)
  • 2021-02-13 11:32

    Depends on database various method can be used.

    PostgreSQL has a nice feature -- series.

    To get what you want just want:

    SELECT * FROM generate_series(1, NUM);
    
    0 讨论(0)
提交回复
热议问题