How to generate a range of numbers between two numbers?

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

    Here's what I came up with:

    create or alter function dbo.fn_range(@start int, @end int)  returns table
    return
    with u2(n) as (
        select n 
        from (VALUES (0),(1),(2),(3)) v(n)
    ), 
    u8(n) as (
        select
            x0.n | x1.n * 4 | x2.n * 16 | x3.n * 64 as n
        from u2 x0, u2 x1, u2 x2, u2 x3
    )
    select 
        @start + s.n as n
    from (
        select
            x0.n | isnull(x1.n, 0) * 256 | isnull(x2.n, 0) * 65536 as n
        from u8 x0 
        left join u8 x1 on @end-@start > 256
        left join u8 x2 on @end-@start > 65536
    ) s
    where s.n < @end - @start
    

    Generates up to 2^24 values. Join conditions keep it fast for small values.

提交回复
热议问题