SQL Query to return N rows from dual

前端 未结 10 2024
盖世英雄少女心
盖世英雄少女心 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条回答
  •  萌比男神i
    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

提交回复
热议问题