Technical Article

Get a range of numbers

and ,

The function needs two parameters (two numbers) which will be refered as lower and upper bounds of sequence of numbers.

It returns an ordered sequence of numbers including the bounds.

Enjoy it.

-- =============================================

-- Author:        Bernabe Diaz

-- Description:    get a sequence of numbers

-- =============================================

CREATE FUNCTION getRangeOfNumbers

(

@f int,@u int

    

)

RETURNS 

@t TABLE 

(

    n INT

)

AS

BEGIN

    -- Fill the table variable with the rows for your result set

        DECLARE    @N INT, @SGN int;

        SET        @N = @u-@f+1;

        SELECT @SGN=CASE WHEN @u>@f THEN 0 ELSE 1 END

        IF @u>@f 

        BEGIN

            SET        @N =     @u-@f+1

        END

        ELSE IF @f>@u 

        BEGIN

            SET        @N =     ABS(@f-@u)+1

            SET        @f=@u

        END

        

        IF @SGN =0

        

        BEGIN

        

            INSERT INTO @t

            SELECT N

            FROM

            (

            SELECT TOP (@N) ROW_NUMBER() OVER(ORDER BY (SELECT 1))+@f-1 N

            FROM        master.sys.columns syst1 

            CROSS JOIN    master.sys.columns syst2

            CROSS JOIN    master.sys.columns syst3

            ) x

            ORDER BY N ASC

        END

        ELSE

        BEGIN

            INSERT INTO @t

            SELECT N

            FROM

            (

            SELECT TOP (@N) ROW_NUMBER() OVER(ORDER BY (SELECT 1))+@f-1 N

            FROM        master.sys.columns syst1 

            CROSS JOIN    master.sys.columns syst2 

            CROSS JOIN    master.sys.columns syst3

            ) x

            ORDER BY N DESC

        END

    RETURN 

END

Rate

2.2 (5)

You rated this post out of 5. Change rating

Share

Share

Rate

2.2 (5)

You rated this post out of 5. Change rating