Click here to Skip to main content
15,908,166 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a dropdown with salary range such as

INR. 10000 to 15000
INR. 15001 to 20000

1)how to search on a range by a range?

ex: Let I am searching 12000-20000 range
Now I have two ranges in database 10000-15000 and 15001-20000.
So I should get the two ranges as a result of my query.

My question is,is there any single sql query to do this type of select statement?
Posted
Comments
DamithSL 10-Nov-14 9:13am    
if you store range as string in single column, first thing you need to do is change add two columns with relevant number type and insert range minimum value in one column and maximum value in another column.
souvikcode 18-Dec-14 4:29am    
I already have done in that way,means I have two cols for max and min.Just need the query if any single query exists.
Sinisa Hajnal 10-Nov-14 9:30am    
After you do that do:
SELECTwhatever, columns, you, need FROM YOUR_TABLE WHERE
minValue BETWEEN lowerRange and upperRange OR maxValue between lowerRange and upperRange OR (lowerRange BETWEEN minValue AND maxValue AND upperRange between minValue and maxValue;

Where min/max Value are your table columns and lower and upper range are values of your search. That is, you're asking for those that intersect the range or those that contain the range in its entirety.
Tomas Takac 10-Nov-14 10:02am    
How does the table storing ranges look like?

Yes, you can, but you need to create stored procedure[^].

First option option - by passing 2 parameters:
SQL
CREATE PROCEDURE GetSalaryFromRange()
    @salFrom DECIMAL(8,0),
    @salTo DECIMAL(8,0)
AS
BEGIN 
    SELECT EmployeeName, Salary
    From TableName
    WHERE Salary BETWEEN @salFrom AND @salTo
END


Second option - by passing 1 parameter:
SQL
CREATE PROCEDURE GetSalaryFromStringRange()
    @stringRange VARCHAR(30)
AS
BEGIN 
    DECLARE @salFrom DECIMAL(8,0) = CONVERT(DECIMAL(8,0), LEFT(@stringRange, CHARINDEX('-', @stringRange) -1))
    DECLARE @salTo DECIMAL(8,0) = CONVERT(DECIMAL(8,0), RIGHT(@stringRange, CHARINDEX('-', @stringRange) +1), LEN(@stringRange) - CHARINDEX('-', @stringRange))

    SELECT EmployeeName, Salary
    From TableName
    WHERE Salary BETWEEN @salFrom AND @salTo
END


How to call it from code?
Walkthrough: Using Only Stored Procedures (C#)[^]
How to: Execute a Stored Procedure that Returns Rows[^]
 
Share this answer
 
Assuming you have two parameters for upper and lower bound of the range you are searching and your table is named SalaryRange with two columns LowerBound & UpperBound. This code is for SQL Server.
SQL
SELECT * FROM SalaryRange sr
WHERE sr.LowerBound <= @UpperBound 
  AND sr.UpperBound >= @LowerBound
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900