Reputation: 163
Lets say I have a range of length that have different price
Length Price
0 - 10 18
11 - 15 20
16 - 20 30
21 - 40 45
41 - infinity 60
How should I store these information in database and how can I retrieve the information when let's say I enter length of 10.625
? How can I get the price of the item with length of 10.625
?
I not sure whether I already solved this problem or not
priceData.Length_End = Math.Ceiling(priceData.Length);
string selectStatement =
"SELECT Price PriceList2 " +
"WHERE @Length_End >= Length_Start AND @Length <= Length_End";
Then I get the first reader's value
SqlDataReader reader = selectCommand.ExecuteReader();
while (reader.Read())
{
price = decimal.Parse(reader["Price_Per_Ton"].ToString());
break;
}
reader.Close();
Please correct me if I was wrong. Thanks for all the responses!
Upvotes: 2
Views: 773
Reputation: 1001
you can change the structure to:
len_start len_end price
0 10 18
11 15 20
16 20 30
21 40 45
41 infinity 60
and run query like:
declare @len decimal
set @len= 10.615
select price from table
Where len_start <= @len and @len < len_end
if you are going to use NULL as infinity, run this query:
select price from table
Where (len_end is not null AND len_start <= @len and @len < len_end) OR
(len_end is null AND len_start <= @len)
Upvotes: 2
Reputation: 98810
Well, I believe you just need to store Length
and you can use BETWEEN
when you want to get Price
column in your queries. Like;
Select Price
From YourTable
Where Length BETWEEN 11 AND 15
Here is SQL Fiddle Demo
.
But this structure is ok only if you know maximum and minimum values of Length
for each range. If you want to store them in database also, you should seperate two different columns your Length
column. Like;
Max_Length | Min_Length | Price
0 | 10 | 18
11 | 15 | 20
16 | 20 | 30
21 | 40 | 45
41 | | 60
Select Price
From YourTable
Where Min_Length < 10.625 AND Max_Length > 10.625
Upvotes: 2