如何为此编写SQL查询?

时间:2011-03-08 05:49:08

标签: sql-server sql-server-2005

我的SQL Server表包含以下列:

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

我在网络表单上有两个文本框。

当用户在文本框2中输入文本框1中的s1from日期2011年3月9日和2011年3月13日的s1to日期之间的日期时,文本框3中的票价将为400其他500

如何为此编写SQL查询?

3 个答案:

答案 0 :(得分:1)

假设您的表示层中的查询是参数化查询(并且您已验证文本框值实际上是日期),您的查询将看起来像(我还假设用户必须选择产品):

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

答案 1 :(得分:0)

这里@ date和@fare是用户定义的变量或输入

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

答案 2 :(得分: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