2011-03-08 312 views
0

我的SQL Server表包含這些列:如何爲此編寫SQL查詢?

ID  Product  fare  s1from   s1to   s1fare 
1  Pen   500  9-Mar-2011  14-Mar-2011  400 
2  copy   800  15-Mar-2011 10-Mar-201  900 
3  Pencil  900  20-Mar-2011 25-Mar-2011  1000 

我有web表單上兩個文本框。

當用戶進入s1from日期9-MAR-2011在TextBox1中和s1to日期之間的日期13-MAR-2011在文本框2然後在textbox3票價將400別的500

如何寫一個SQL查詢爲了這?

+0

我們可以建議你有很多方法來實現這一點,但是你的表格結構看起來不太好。拆分它並使其更好。 – Pradeep 2011-03-08 05:52:50

+0

確實接受了答案 – 2011-03-08 06:14:32

+0

有兩個問題:如果我輸入像「2011-03-01」這樣的日期,會發生什麼?如果我輸入像「2011-03-15」這樣的日期,會發生什麼?也就是說,它會怎麼知道使用'票價'欄中的值與's1fare'欄中的值?用戶是否需要選擇產品? – Thomas 2011-03-08 07:00:36

回答

0

這裏@日期和@fare是用戶定義的變量或輸入

Select * from table 
where (@date between s1from and s1to) 
and fare  = @fare 
0

試試這個

Declare @dateFrom as datetime 
Declare @dateTo as datetime 
set @dateFrom = '03/09/2011' -- this is the value from textbox 1 
set @dateTo = '03/13/2011' -- this is the value from textbox 2 

-- this query returns the fare based on the inputted values on dateFrom and dateTo 
Select 
    TheFare=Case when @dateFrom >= Cast(Convert(varchar(20),s1from,101) as datetime) and 
    @dateTo <= Cast(Convert(varchar(20),s1To,101) as datetime) then 
    s1fare 
    else fare 
    end 
From YourTable 
1

假設從您的表示層的查詢是參數化查詢(並且已經證實文本框的值真的是日期),你的查詢看起來像(我也假設用戶不得不選擇產品):

Select Case 
     When @UserDateValue Between s1from And s1to Then s1fare 
     Else fare 
     End As fare 
From MyTable 
Where Product = @Product