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
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:
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
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
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);