I need to select all numbers N (integers) between @min and @max
Is there any way to achieve that without using a loop of some sort?
Example:
Let’s say @min = 5, @max = 9
I need the following values returned by my SQL query: 5,6,7,8,9
(I’m using MSSQL 2005)
Thanks!!
EDIT:
This is a solution using a custom function, which works fine.
But it seems too much effort having to loop through all numbers manually.
So the question is still, whether it’s achievable without a loop.
CREATE FUNCTION GetAllNBetween
(
@Min int,
@Max int
)
RETURNS @N TABLE(n int)
AS
BEGIN
WHILE @Min <= @Max
BEGIN
INSERT INTO @N VALUES(@Min)
SET @Min = @Min + 1
END
RETURN
END
To be used like this:
SELECT * FROM GetAllNBetween(5, 9)
The query (as suggested by @Eric)
Returns the numbers between 1 and ~3000, on my mostly empty test database. You can add another level of sysobjects to get an insane number of rows. Then it’s a simple matter of filtering this