How to generate a range of numbers between two numbers?

后端 未结 30 2532
执念已碎
执念已碎 2020-11-22 10:16

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

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 10:33

    Here is a generic and relatively fast solution that outputs integers from 1 to @n. It works with any positive integer of @n (very large numbers will cause arithmetic overflow) without needing to add or remove table joins. It doesn't require the use of system tables nor do you to change max recursions.

    declare @n int = 10000 
    
    ;with d as (select * from (values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x (d)),
    n as ( 
        select d x from d where d > 0 and d <= @n
        union all
        select x * 10 + d from n, d where x * 10 + d <= @n
    )
    select x from n 
    

    You can add an order by clause to sort the numbers.

提交回复
热议问题