0

Let's say I have the following database table

id min max 1 0 0 2 1 90 3 91 180 4 181 365 5 366 0 

So, what I need it to happen is this;

If I search for 0, I should get id=1 (min=0, max=0); if I search for 95, I should get id=3 (min=91, max=180); and for anything >=366, I should get id=5;

4 Answers 4

1

How about

SELECT * FROM @Table WHERE (@Value BETWEEN [MIN] AND [MAX]) OR (@Value >= [MIN] AND [MAX] = 0) 

Where @Value is the value you are looking for.

Please note however that more than 1 row might be returned if your [MIN],[MAX] ranges are not unique.

Sign up to request clarification or add additional context in comments.

2 Comments

@Rabin, saw that, and fixed it X-)
Doesn't seem to work for some data. Thank you for helping. I've found my answer below.
1

You can try this

DECLARE @Value INT = 400 SELECT * FROM TABLE WHERE (@Value >= 366 AND Min = 366 ) OR @Value BETWEEN Min AND MAX 

2 Comments

The problem with this solution is what happens if those values change? then you need to adjust the query, where as my solution(below my initial solution) doesn't use any hard coded values. So the question is, will those values change ever? or are they static?
I see what you mean @Johan. The ceiling value of 366 haven't changed in quite of lot of years and I don't anticipate it to change in the near future. You have given me food for thoughts. Thank you.
1

try this:

declare @Search_val int=95; SELECT Id FROM your_table WHERE @Search_val between [min] and [max] OR (@Search_val>min and [max]=0 and [min]!=0) 

Comments

1
SELECT [Id] FROM @Table WHERE (@Value BETWEEN [min] AND [max]) OR (@Value >= [min] AND [max] = -1) 

Is it possible to make the max of the infinite number (ID 5's max) to -1?

if so the above code will work great.

You need a unique way to say that any number higher than the min must be included, and using 0 on both id 1 and 5 isnt unique .

EDIT --> this should work if you can't change to -1

SELECT TOP 1 [Id] FROM @Table WHERE (@Value BETWEEN [min] AND [max]) OR (@Value >= [min] AND [max] = 0) ORDER BY [MIN] DESC 

1 Comment

Have a look at the edit I added, I could clean it up a bit, but I am sure you can see what is happening, and change it as needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.