How to generate a range of numbers between two numbers?

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

    If you don't have a problem installing a CLR assembly in your server a good option is writing a table valued function in .NET. That way you can use a simple syntax, making it easy to join with other queries and as a bonus won't waste memory because the result is streamed.

    Create a project containing the following class:

    using System;
    using System.Collections;
    using System.Data;
    using System.Data.Sql;
    using System.Data.SqlTypes;
    using Microsoft.SqlServer.Server;
    
    namespace YourNamespace
    {
       public sealed class SequenceGenerator
        {
            [SqlFunction(FillRowMethodName = "FillRow")]
            public static IEnumerable Generate(SqlInt32 start, SqlInt32 end)
            {
                int _start = start.Value;
                int _end = end.Value;
                for (int i = _start; i <= _end; i++)
                    yield return i;
            }
    
            public static void FillRow(Object obj, out int i)
            {
                i = (int)obj;
            }
    
            private SequenceGenerator() { }
        }
    }
    

    Put the assembly somewhere on the server and run:

    USE db;
    CREATE ASSEMBLY SqlUtil FROM 'c:\path\to\assembly.dll'
    WITH permission_set=Safe;
    
    CREATE FUNCTION [Seq](@start int, @end int) 
    RETURNS TABLE(i int)
    AS EXTERNAL NAME [SqlUtil].[YourNamespace.SequenceGenerator].[Generate];
    

    Now you can run:

    select * from dbo.seq(1, 1000000)
    

提交回复
热议问题