How to generate a range of numbers between two numbers?

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

    This is what I do, it's pretty fast and flexible and not a lot of code.

    DECLARE @count  int =   65536;
    DECLARE @start  int =   11;
    DECLARE @xml    xml =   REPLICATE(CAST('' AS nvarchar(max)), @count);
    
    ; WITH GenerateNumbers(Num) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY @count) + @start - 1
        FROM    @xml.nodes('/x') X(T)
    )
    SELECT  Num
    FROM    GenerateNumbers;
    

    Note that (ORDER BY @count) is a dummy. It doesn't do anything but ROW_NUMBER() requires an ORDER BY.

    Edit: I realized that the original question was to get a range from x to y. My script can be modified like this to get a range:

    DECLARE @start  int =   5;
    DECLARE @end    int =   21;
    DECLARE @xml    xml =   REPLICATE(CAST('' AS nvarchar(max)), @end - @start + 1);
    
    ; WITH GenerateNumbers(Num) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY @end) + @start - 1
        FROM    @xml.nodes('/x') X(T)
    )
    SELECT  Num
    FROM    GenerateNumbers;
    

提交回复
热议问题