How to generate a range of numbers between two numbers?

后端 未结 30 2279
执念已碎
执念已碎 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:25

    slartidan's answer can be improved, performance wise, by eliminating all references to the cartesian product and using ROW_NUMBER() instead (execution plan compared):

    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS n FROM 
    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x1(x),
    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x2(x),
    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x3(x),
    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x4(x),
    (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x5(x)
    ORDER BY n
    

    Wrap it inside a CTE and add a where clause to select desired numbers:

    DECLARE @n1 AS INT = 100;
    DECLARE @n2 AS INT = 40099;
    WITH numbers AS (
        SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS n FROM 
        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x1(x),
        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x2(x),
        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x3(x),
        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x4(x),
        (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) x5(x)
    )
    SELECT numbers.n
    FROM numbers
    WHERE n BETWEEN @n1 and @n2
    ORDER BY n
    

提交回复
热议问题