I have two numbers as input from the user, like for example 1000
and 1050
.
How do I generate the numbers between these two numbers, using a sql query, in seperate rows? I want this:
1000
1001
1002
1003
.
.
1050
I have two numbers as input from the user, like for example 1000
and 1050
.
How do I generate the numbers between these two numbers, using a sql query, in seperate rows? I want this:
1000
1001
1002
1003
.
.
1050
This completed for me in 36 seconds on our DEV server. Like Brian's answer, focusing on filtering to the range is important from within the query; a BETWEEN still tries to generate all the initial records prior to the lower bound even though it doesn't need them.
Note that ROW_NUMBER is a bigint, so we can't go over 2^^64 (==16^^16) generated records with any method that uses it. This query therefore respects the same upper limit on generated values.
recursive CTE in exponential size (even for default of 100 recursion, this can build up to 2^100 numbers):
Demo
Note that this table has a maximum of 2048 because then the numbers have gaps.
Here's a slightly better approach using a system view(since from SQL-Server 2005):
Demo
or use a custom a number-table. Credits to Aaron Bertrand, i suggest to read the whole article: Generate a set or sequence without loops
The best way is using recursive ctes.
saludos.
Select non-persisted values with the
VALUES
keyword. Then useJOIN
s to generate lots and lots of combinations (can be extended to create hundreds of thousands of rows and beyond).Demo
A shorter alternative, that is not as easy to understand:
Demo
an alternative solution is recursive CTE: