How to create increment field in select statement [duplicate] - sql

Is there any way to select the numbers (integers) that are included between two numbers with SQL in Oracle; I don't want to create PL/SQL procedure or function.
For example I need to get the numbers between 3 and 10. The result will be the values 3,4,5,6,7,8,9,10.
Thx.

This trick with Oracle's DUAL table also works:
SQL> select n from
2 ( select rownum n from dual connect by level <= 10)
3 where n >= 3;
N
----------
3
4
5
6
7
8
9
10

The first thing I do when I create a new database is to create and populate some basic tables.
One is a list of all integers between -N and N, another is a list of dates 5 years in the past through 10 years in the future (a scheduled job can continue creating these as needed, going forward) and the last is a list of all hours throughout the day. For example, the inetgers:
create table numbers (n integer primary key);
insert into numbers values (0);
insert into numbers select n+1 from numbers; commit;
insert into numbers select n+2 from numbers; commit;
insert into numbers select n+4 from numbers; commit;
insert into numbers select n+8 from numbers; commit;
insert into numbers select n+16 from numbers; commit;
insert into numbers select n+32 from numbers; commit;
insert into numbers select n+64 from numbers; commit;
insert into numbers select n+128 from numbers; commit;
insert into numbers select n+256 from numbers; commit;
insert into numbers select n+512 from numbers; commit;
insert into numbers select n+1024 from numbers; commit;
insert into numbers select n+2048 from numbers; commit;
insert into numbers select n+4096 from numbers; commit;
insert into numbers select n+8192 from numbers; commit;
insert into numbers select -n from numbers where n > 0; commit;
This is for DB2/z which has automatic transaction start which is why it seems to have naked commits.
Yes, it takes up a (minimal) space but it makes queries much easier to write, simply by selecting values from those tables. It's also very portable across pretty much any SQL-based DBMS.
Your particular query would then be a simple:
select n from numbers where n >=3 and n <= 10;
The hour figures and date ranges are quite useful for the sort of reporting applications we work on. It allows us to create zero entries for those hours of the day (or dates) which don't have any real data so that, instead of (where there's no data on the second of the month):
Date | Quantity
-----------+---------
2009-01-01 | 7
2009-01-03 | 27
2009-01-04 | 6
we can instead get:
Date | Quantity
-----------+---------
2009-01-01 | 7
2009-01-02 | 0
2009-01-03 | 27
2009-01-04 | 6

SQL> var N_BEGIN number
SQL> var N_END number
SQL> exec :N_BEGIN := 3; :N_END := 10
PL/SQL procedure successfully completed.
SQL> select :N_BEGIN + level - 1 n
2 from dual
3 connect by level <= :N_END - :N_BEGIN + 1
4 /
N
----------
3
4
5
6
7
8
9
10
8 rows selected.
This uses the same trick as Tony's. Note that when you are using SQL*Plus 9, you have to make this query an inline view as Tony showed you. In SQL*Plus 10 or higher, the above is sufficient.
Regards,
Rob.

You can use the MODEL clause for this.
SELECT c1 from dual
MODEL DIMENSION BY (1 as rn) MEASURES (1 as c1)
RULES ITERATE (7)
(c1[ITERATION_NUMBER]=ITERATION_NUMBER+7)

this single line query will help you,
select level lvl from dual where level<:upperbound and
level >:lowerbound connect by level<:limt
For your case:
select level lvl from dual where level<10 and level >3 connect by level<11
let me know if any clarification.

One way to generate numbers from range is to use XMLTABLE('start to end'):
SELECT TO_NUMBER(column_value) integer_value
FROM XMLTABLE('3 to 10');
I added TO_NUMBER because COLUMN_VALUE is a string
DBFiddle Demo

Or you can use Between
Select Column1 from dummy_table where Column2 Between 3 and 10

Gary, to show the result that he explained, the model query will be:
SELECT c1
FROM DUAL
MODEL DIMENSION BY (1 as rn)
MEASURES (1 as c1)
RULES ITERATE (8)
(c1[ITERATION_NUMBER]=ITERATION_NUMBER+3)
ORDER BY rn
;)
I always use:
SELECT (LEVEL - 1) + 3 as result
FROM Dual
CONNECT BY Level <= 8
Where 3 is the start number and 8 is the number of "iterations".

This is a late addition. But the solution seems to be more elegant and easier to use.
It uses a pipelined function that has to be installed once:
CREATE TYPE number_row_type AS OBJECT
(
num NUMBER
);
CREATE TYPE number_set_type AS TABLE OF number_row_type;
CREATE OR REPLACE FUNCTION number_range(p_start IN PLS_INTEGER, p_end IN PLS_INTEGER)
RETURN number_set_type
PIPELINED
IS
out_rec number_row_type := number_row_type(NULL);
BEGIN
FOR i IN p_start .. p_end LOOP
out_rec.num := i;
pipe row(out_rec);
END LOOP;
END number_range;
/
Then you can use it like this:
select * from table(number_range(1, 10));
NUM
---
1
2
3
4
5
6
7
8
9
10
The solution is Oracle specific.

I just did a table valued function to do this in SQL server, if anyone is interested, this works flawlessly.
CREATE FUNCTION [dbo].[NumbersBetween]
(
#StartN int,
#EndN int
)
RETURNS
#NumberList table
(
Number int
)
AS
BEGIN
WHILE #StartN <= #EndN
BEGIN
insert into #NumberList
VALUES (#StartN)
set #StartN = #StartN + 1
END
Return
END
GO
If you run the query: "select * from dbo.NumbersBetween(1,5)" (w/o the quotes of course) the result will be
Number
-------
1
2
3
4
5

I want to share an usefull query that converts a string of comma and '-' separated list of numbers into a the equivalent expanded list of numbers:
An example that converts '1,2,3,50-60' into
1
2
3
50
51
...
60
select distinct * from (SELECT (LEVEL - 1) + mini as result FROM (select REGEXP_SUBSTR (value, '[^-]+', 1, 1)mini ,nvl(REGEXP_SUBSTR (value, '[^-]+', 1, 2),0) maxi from (select REGEXP_SUBSTR (value, '[^,]+', 1, level) as value from (select '1,2,3,50-60' value from dual) connect by level <= length(regexp_replace(value,'[^,]*'))+1)) CONNECT BY Level <= (maxi-mini+1)) order by 1 asc;
You may use it as a view and parametrize the '1,2,3,50-60' string

create table numbers (value number);
declare
x number;
begin
for x in 7 .. 25
loop
insert into numbers values (x);
end loop;
end;
/

In addition to the answers already provided, it is possible to combine the listagg function with connect by to obtain the result in the format mentioned in the question. See a code example below:
SELECT
DBMS_LOB.SUBSTR(LISTAGG(S.INTEGERS,',' ) WITHIN GROUP (ORDER BY S.INTEGERS), 300,1) RESULT
FROM
(SELECT
INTEGERS
FROM
( SELECT ROWNUM INTEGERS FROM DUAL CONNECT BY LEVEL <= 10)
WHERE
INTEGERS >= 3
) S;
OutPut:
SQL>
RESULT
----------------
3,4,5,6,7,8,9,10

Related

In a oracle procedure to get the maximum number from Varchar data type field having a prefix

I have a table called ORG, In which I have a field called ORG_ID, I need to get the maximum value from the ORG ID for a specific prefix. For example
Table ORG
ORG_ID
ORG_NAME
AB1
Apple
AB2
Google
HQ1
Microsoft
AB3
Tesla
HQ2
Amazon
Now, I want to get the maximum numeric value associated with the prefix AB, I am using below
select max(ORG.ORG_ID)
from ORG
where ORG_ID like 'AB'
It returns AB3 I can use regular expression to get the numeric value 3.
My concern is does the above select query always guarantee the max numeric value with the sequence AB.
code
DECLARE
v_max_number NUMBER;
v_max_org_id VARCHAR2 (20);
v_max_var VARCHAR2 (20);
CURSOR curb IS
SELECT org_id, name
FROM tableb
FOR UPDATE;
cbr curb%ROWTYPE;
i NUMBER := 1;
BEGIN
SELECT MAX (tablea.org_id)
INTO v_max_org_id
FROM tablea
WHERE org_id LIKE 'AB%';
SELECT REGEXP_SUBSTR (v_max_org_id, '\d+') INTO v_max_number FROM DUAL;
SELECT REGEXP_SUBSTR (v_max_org_id, '\D+') INTO v_max_var FROM DUAL;
-- For Loop to write data to Table B
OPEN curb;
LOOP
FETCH curb INTO cbr;
EXIT WHEN curb%NOTFOUND;
v_max_org_id := v_max_var || TO_CHAR (v_max_number + i);
UPDATE tableb
SET org_id = v_max_org_id
WHERE CURRENT OF curb;
i := i + 1;
END LOOP;
END;
You asked:
My concern is does the above select query always guarantee the max numeric value with the sequence AB.
The "above query" is
select max(ORG.ORG_ID)
from ORG
where ORG_ID like 'AB'
So, does it return MAX numeric value? I don't think so:
SQL> with test (id) as
2 (select 'AB5' from dual union all
3 select 'AB15' from dual union all
4 select 'AB1280' from dual --> 1280 is MAX (compared to 5 and 15)
5 )
6 select max(id)
7 from test
8 where id like 'AB%'
9 /
MAX(ID
------
AB5 --> this is what your query returns
SQL>
Based on sample data in this (and previous) question you posted, consider
SQL> with test (id) as
2 (select 'AB5' from dual union all
3 select 'AB15' from dual union all
4 select 'AB1280' from dual
5 )
6 select max(to_number(regexp_substr(id, '\d+$'))) result
7 from test
8 where id like 'AB%'
9 /
RESULT
----------
1280
SQL>

PL/SQL How to obtain count of the table I am querying from? How to use NEW with COUNT?

below is my code that will trigger when a new row in Trip is inserted. Then it will update on the column totalTripMade in the Driver table.
CREATE OR REPLACE TRIGGER UPDATE_TOTAL_TRIPS_MADE
AFTER INSERT
ON TRIP
FOR EACH ROW
DECLARE
tripsDone NUMBER(6);
driverL# NUMBER(12);
BEGIN
--Find the L# of the Driver performing the INSERT into the Trip table
SELECT D.L# INTO driverL#
FROM DRIVER D
WHERE D.L# =: NEW.L#;
--Find the number of trips done by the driver (Error occured here)
SELECT COUNT(T#) INTO tripsDone
FROM TRIP T
WHERE NEW.L# =: driverL#;
--Then update the totaltripmade by the driver
UPDATE
DRIVER
SET
totalTripMade = tripsDone
WHERE
L# = driverL#;
END UPDATE_TOTAL_TRIPS_MADE;
/
However, there is compilation error due to not able to query TRIP until the trigger is completed.
So, I tried changing the select count statement to like that:
SELECT COUNT(*) INTO tripsDone
FROM TRIP T
WHERE driverL# =: NEW.L#;
But it did not work too. I am not sure how can I work around to get the total number of rows in the table Trip with the driverL# that triggered the trigger.
For solving this problem, you should probably NOT use a trigger. Just write a query for counting the "trips". Example:
Tables
create table driver (
id number generated always as identity start with 1 primary key
, surname varchar2( 50 )
-- , ttm number -- total trips made: redundant!
) ;
create table trip (
id number generated always as identity start with 1000 primary key
, from_ varchar2( 50 )
, to_ varchar2( 50 )
, driver number references driver( id )
) ;
Test data: DRIVER
insert into driver( surname )
select
'driver_' || to_char( level )
from dual
connect by level <= 10 ;
select * from driver ;
ID SURNAME
1 driver_1
2 driver_2
3 driver_3
4 driver_4
5 driver_5
6 driver_6
7 driver_7
8 driver_8
9 driver_9
10 driver_10
Test data: TRIP
begin
for i in 1 .. 10
loop
insert into trip ( from_, to_, driver ) values (
'departure_' || to_char( i )
, 'arrival_' || to_char( i )
, mod( i, 3 ) + 1
) ;
end loop ;
commit ;
end ;
/
SQL> select * from trip ;
ID FROM_ TO_ DRIVER
1000 departure_1 arrival_1 2
1001 departure_2 arrival_2 3
1002 departure_3 arrival_3 1
1003 departure_4 arrival_4 2
1004 departure_5 arrival_5 3
1005 departure_6 arrival_6 1
1006 departure_7 arrival_7 2
1007 departure_8 arrival_8 3
1008 departure_9 arrival_9 1
1009 departure_10 arrival_10 2
Query: find the "trip count"
select D.id, D.surname, count(*) as trips_made
from driver D
join trip T on D.id = T.driver
group by D.id, D.surname ;
-- result
ID SURNAME TRIPS_MADE
1 driver_1 3
2 driver_2 4
3 driver_3 3
However, if you want to learn about triggers, you will find that a "row level trigger" will give you "mutating table" errors. When using a "table level" trigger, you cannot reference :NEW and :OLD. What you need is a COMPOUND TRIGGER. You can find numerous discussions about this problem. Apart from consulting the Oracle PL/SQL documentation, it may be worth your while looking that the examples written by T Hall eg here, and S Feuerstein eg here.
The dbfiddle here contains the code used for this answer, and a third example table called DRIVERV2 plus examples of the above mentioned trigger types (and typical error messages).

Oracle 12c: Can I invoke a function from a WITH clause which both takes and returns a table?

I want to write a PL/SQL function which can be used in a variety of queries, particular the subqueries of a WITH clause. The tricky part is that I want the function to both receive and return a one-column TABLE (or CURSOR) of information.
Details: imagine that this function just sorts a list of employee IDs according to some very complicated criteria. We'd have this:
My function is called SORT_EMPLOYEES
My function takes a 1-column table of employee IDs (emp_id) as input.
This input type is probably a TABLE type EMP_T_TYPE.
This return type is probably also a TABLE type EMP_T_TYPE.
So far so good, I hope.
Now, I think that I can use the output of the function with the TABLE operator pretty much anywhere; e.g.:
WITH
wanted_emps AS (...), -- find employees we want, as table of emp_id
ranked_emps AS (
SELECT rownum() as rank, emp_id
FROM TABLE(SORT_EMPLOYEES(...???...))
),
...
The problem is: how can I get the list of employees from 'wanted_emps' and make it the input of SORT_EMPLOYEES? What goes in the "...???..." above? Is this even possible?
Please note that I want this to be used from plain SQL, especially from subqueries of WITH clauses as shown above -- not from PL/SQL. Thanks!
Here is an example of how to COLLECT values into a collection which can then be passed to a FUNCTION that returns another collection:
Oracle Setup:
CREATE TYPE numbers_table AS TABLE OF NUMBER;
CREATE TABLE test_data ( grp, value ) AS
SELECT 1, 1 FROM DUAL UNION ALL
SELECT 1, 2 FROM DUAL UNION ALL
SELECT 1, 3 FROM DUAL UNION ALL
SELECT 2, 4 FROM DUAL UNION ALL
SELECT 2, 5 FROM DUAL UNION ALL
SELECT 3, 6 FROM DUAL;
Query:
WITH FUNCTION square( i_numbers IN numbers_table ) RETURN numbers_table
IS
p_numbers numbers_table := numbers_table();
p_count PLS_INTEGER;
BEGIN
IF i_numbers IS NULL THEN
p_count := 0;
ELSE
p_count := i_numbers.COUNT;
END IF;
p_numbers.EXTEND( p_count );
FOR i IN 1 .. p_count LOOP
p_numbers(i) := i_numbers(i) * i_numbers(i);
END LOOP;
RETURN p_numbers;
END;
collected_rows ( grp, grouped_values ) AS (
SELECT grp,
CAST(
COLLECT( value ORDER BY value )
AS numbers_table
)
FROM test_data
GROUP BY grp
)
SELECT c.grp,
t.COLUMN_VALUE AS squared_value
FROM collected_rows c
CROSS JOIN
TABLE( square( c.grouped_values ) ) t;
Output:
GRP | SQUARED_VALUE
--: | ------------:
1 | 1
1 | 4
1 | 9
2 | 16
2 | 25
3 | 36
db<>fiddle here

How can I select from list of values in Oracle

I am referring to this stackoverflow answer:
How can I select from list of values in SQL Server
How could something similar be done in Oracle?
I've seen the other answers on this page that use UNION and although this method technically works, it's not what I would like to use in my case.
So I would like to stay with syntax that more or less looks like a comma-separated list of values.
UPDATE regarding the create type table answer:
I have a table:
CREATE TABLE BOOK
( "BOOK_ID" NUMBER(38,0)
)
I use this script but it does not insert any rows to the BOOK table:
create type number_tab is table of number;
INSERT INTO BOOK (
BOOK_ID
)
SELECT A.NOTEBOOK_ID FROM
(select column_value AS NOTEBOOK_ID from table (number_tab(1,2,3,4,5,6))) A
;
Script output:
TYPE number_tab compiled
Warning: execution completed with warning
But if I use this script it does insert new rows to the BOOK table:
INSERT INTO BOOK (
BOOK_ID
)
SELECT A.NOTEBOOK_ID FROM
(SELECT (LEVEL-1)+1 AS NOTEBOOK_ID FROM DUAL CONNECT BY LEVEL<=6) A
;
You don't need to create any stored types, you can evaluate Oracle's built-in collection types.
select distinct column_value from table(sys.odcinumberlist(1,1,2,3,3,4,4,5))
If you are seeking to convert a comma delimited list of values:
select column_value
from table(sys.dbms_debug_vc2coll('One', 'Two', 'Three', 'Four'));
-- Or
select column_value
from table(sys.dbms_debug_vc2coll(1,2,3,4));
If you wish to convert a string of comma delimited values then I would recommend Justin Cave's regular expression SQL solution.
Starting from Oracle 12.2, you don't need the TABLE function, you can directly select from the built-in collection.
SQL> select * FROM sys.odcinumberlist(5,2,6,3,78);
COLUMN_VALUE
------------
5
2
6
3
78
SQL> select * FROM sys.odcivarchar2list('A','B','C','D');
COLUMN_VALUE
------------
A
B
C
D
There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select '1,2,3,a,b,c,d' str from dual
3 )
4 select regexp_substr(str,'[^,]+',1,level) element
5 from x
6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /
ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d
7 rows selected.
Or in PL/SQL
SQL> create type str_tbl is table of varchar2(100);
2 /
Type created.
SQL> create or replace function parse_list( p_list in varchar2 )
2 return str_tbl
3 pipelined
4 is
5 begin
6 for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
7 from dual
8 connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
9 loop
10 pipe row( x.element );
11 end loop
12 return;
13 end;
14
15 /
Function created.
SQL> select *
2 from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));
COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f
9 rows selected.
You can do this:
create type number_tab is table of number;
select * from table (number_tab(1,2,3,4,5,6));
The column is given the name COLUMN_VALUE by Oracle, so this works too:
select column_value from table (number_tab(1,2,3,4,5,6));
Hi it is also possible for Strings with XML-Table
SELECT trim(COLUMN_VALUE) str FROM xmltable(('"'||REPLACE('a1, b2, a2, c1', ',', '","')||'"'));
[Deprecated] - Just to add for the op,
The issue with your second code it seems to be that you haven't defined there your "number_tab" type.
AS :
CREATE type number_tab is table of number;
SELECT a.notebook_id FROM (
SELECT column_value AS notebook_id FROM table (number_tab(1,2,3,4,5,6) ) ) a;
INSERT INTO BOOK ( BOOK_ID )
SELECT a.notebook_id FROM (
SELECT column_value AS notebook_id FROM table (number_tab(1,2,3,4,5,6) ) ) a;
DROP type number_tab ;
Sorry, I couldn't reproduce your error, could you send us the version of oracle used and the same code used for the procedure in the first instance?, that could help. All the best.

ORACLE SQL:Get all integers between two numbers

Is there any way to select the numbers (integers) that are included between two numbers with SQL in Oracle; I don't want to create PL/SQL procedure or function.
For example I need to get the numbers between 3 and 10. The result will be the values 3,4,5,6,7,8,9,10.
Thx.
This trick with Oracle's DUAL table also works:
SQL> select n from
2 ( select rownum n from dual connect by level <= 10)
3 where n >= 3;
N
----------
3
4
5
6
7
8
9
10
The first thing I do when I create a new database is to create and populate some basic tables.
One is a list of all integers between -N and N, another is a list of dates 5 years in the past through 10 years in the future (a scheduled job can continue creating these as needed, going forward) and the last is a list of all hours throughout the day. For example, the inetgers:
create table numbers (n integer primary key);
insert into numbers values (0);
insert into numbers select n+1 from numbers; commit;
insert into numbers select n+2 from numbers; commit;
insert into numbers select n+4 from numbers; commit;
insert into numbers select n+8 from numbers; commit;
insert into numbers select n+16 from numbers; commit;
insert into numbers select n+32 from numbers; commit;
insert into numbers select n+64 from numbers; commit;
insert into numbers select n+128 from numbers; commit;
insert into numbers select n+256 from numbers; commit;
insert into numbers select n+512 from numbers; commit;
insert into numbers select n+1024 from numbers; commit;
insert into numbers select n+2048 from numbers; commit;
insert into numbers select n+4096 from numbers; commit;
insert into numbers select n+8192 from numbers; commit;
insert into numbers select -n from numbers where n > 0; commit;
This is for DB2/z which has automatic transaction start which is why it seems to have naked commits.
Yes, it takes up a (minimal) space but it makes queries much easier to write, simply by selecting values from those tables. It's also very portable across pretty much any SQL-based DBMS.
Your particular query would then be a simple:
select n from numbers where n >=3 and n <= 10;
The hour figures and date ranges are quite useful for the sort of reporting applications we work on. It allows us to create zero entries for those hours of the day (or dates) which don't have any real data so that, instead of (where there's no data on the second of the month):
Date | Quantity
-----------+---------
2009-01-01 | 7
2009-01-03 | 27
2009-01-04 | 6
we can instead get:
Date | Quantity
-----------+---------
2009-01-01 | 7
2009-01-02 | 0
2009-01-03 | 27
2009-01-04 | 6
SQL> var N_BEGIN number
SQL> var N_END number
SQL> exec :N_BEGIN := 3; :N_END := 10
PL/SQL procedure successfully completed.
SQL> select :N_BEGIN + level - 1 n
2 from dual
3 connect by level <= :N_END - :N_BEGIN + 1
4 /
N
----------
3
4
5
6
7
8
9
10
8 rows selected.
This uses the same trick as Tony's. Note that when you are using SQL*Plus 9, you have to make this query an inline view as Tony showed you. In SQL*Plus 10 or higher, the above is sufficient.
Regards,
Rob.
You can use the MODEL clause for this.
SELECT c1 from dual
MODEL DIMENSION BY (1 as rn) MEASURES (1 as c1)
RULES ITERATE (7)
(c1[ITERATION_NUMBER]=ITERATION_NUMBER+7)
this single line query will help you,
select level lvl from dual where level<:upperbound and
level >:lowerbound connect by level<:limt
For your case:
select level lvl from dual where level<10 and level >3 connect by level<11
let me know if any clarification.
One way to generate numbers from range is to use XMLTABLE('start to end'):
SELECT TO_NUMBER(column_value) integer_value
FROM XMLTABLE('3 to 10');
I added TO_NUMBER because COLUMN_VALUE is a string
DBFiddle Demo
Or you can use Between
Select Column1 from dummy_table where Column2 Between 3 and 10
Gary, to show the result that he explained, the model query will be:
SELECT c1
FROM DUAL
MODEL DIMENSION BY (1 as rn)
MEASURES (1 as c1)
RULES ITERATE (8)
(c1[ITERATION_NUMBER]=ITERATION_NUMBER+3)
ORDER BY rn
;)
I always use:
SELECT (LEVEL - 1) + 3 as result
FROM Dual
CONNECT BY Level <= 8
Where 3 is the start number and 8 is the number of "iterations".
This is a late addition. But the solution seems to be more elegant and easier to use.
It uses a pipelined function that has to be installed once:
CREATE TYPE number_row_type AS OBJECT
(
num NUMBER
);
CREATE TYPE number_set_type AS TABLE OF number_row_type;
CREATE OR REPLACE FUNCTION number_range(p_start IN PLS_INTEGER, p_end IN PLS_INTEGER)
RETURN number_set_type
PIPELINED
IS
out_rec number_row_type := number_row_type(NULL);
BEGIN
FOR i IN p_start .. p_end LOOP
out_rec.num := i;
pipe row(out_rec);
END LOOP;
END number_range;
/
Then you can use it like this:
select * from table(number_range(1, 10));
NUM
---
1
2
3
4
5
6
7
8
9
10
The solution is Oracle specific.
I just did a table valued function to do this in SQL server, if anyone is interested, this works flawlessly.
CREATE FUNCTION [dbo].[NumbersBetween]
(
#StartN int,
#EndN int
)
RETURNS
#NumberList table
(
Number int
)
AS
BEGIN
WHILE #StartN <= #EndN
BEGIN
insert into #NumberList
VALUES (#StartN)
set #StartN = #StartN + 1
END
Return
END
GO
If you run the query: "select * from dbo.NumbersBetween(1,5)" (w/o the quotes of course) the result will be
Number
-------
1
2
3
4
5
I want to share an usefull query that converts a string of comma and '-' separated list of numbers into a the equivalent expanded list of numbers:
An example that converts '1,2,3,50-60' into
1
2
3
50
51
...
60
select distinct * from (SELECT (LEVEL - 1) + mini as result FROM (select REGEXP_SUBSTR (value, '[^-]+', 1, 1)mini ,nvl(REGEXP_SUBSTR (value, '[^-]+', 1, 2),0) maxi from (select REGEXP_SUBSTR (value, '[^,]+', 1, level) as value from (select '1,2,3,50-60' value from dual) connect by level <= length(regexp_replace(value,'[^,]*'))+1)) CONNECT BY Level <= (maxi-mini+1)) order by 1 asc;
You may use it as a view and parametrize the '1,2,3,50-60' string
create table numbers (value number);
declare
x number;
begin
for x in 7 .. 25
loop
insert into numbers values (x);
end loop;
end;
/
In addition to the answers already provided, it is possible to combine the listagg function with connect by to obtain the result in the format mentioned in the question. See a code example below:
SELECT
DBMS_LOB.SUBSTR(LISTAGG(S.INTEGERS,',' ) WITHIN GROUP (ORDER BY S.INTEGERS), 300,1) RESULT
FROM
(SELECT
INTEGERS
FROM
( SELECT ROWNUM INTEGERS FROM DUAL CONNECT BY LEVEL <= 10)
WHERE
INTEGERS >= 3
) S;
OutPut:
SQL>
RESULT
----------------
3,4,5,6,7,8,9,10