Sql server 2005 使用Where子句中Select Case语句的结果字段

Sql server 2005 使用Where子句中Select Case语句的结果字段,sql-server-2005,Sql Server 2005,我有一个proc,我想添加一个参数-该参数将被称为@AmountType。然后我想将@AmountType参数添加到我的where子句中,这样我就可以过滤不同的金额类型。棘手的是,我希望@AmountType的值是select的case语句部分的结果。 所以,只显示AmountType1记录,或者只显示AmountType2记录,等等。显然,我不能只显示@AmountType=Amounts,因为Amounts不是一个真正的列 有什么办法可以做到这一点吗 我的声明如下: ALTER PROCED

我有一个proc,我想添加一个参数-该参数将被称为@AmountType。然后我想将@AmountType参数添加到我的where子句中,这样我就可以过滤不同的金额类型。棘手的是,我希望@AmountType的值是select的case语句部分的结果。 所以,只显示AmountType1记录,或者只显示AmountType2记录,等等。显然,我不能只显示@AmountType=Amounts,因为Amounts不是一个真正的列

有什么办法可以做到这一点吗

我的声明如下:

ALTER PROCEDURE spProc1
  @Date datetime
AS
BEGIN

    Select 
      location, 
      workDate, 
      case 
        when dollarAmount1 - dollarAmount2 < 0 Then 'AmountType1'
        when dollarAmount1 - dollarAmount2 > 0 Then 'AmountType2'
        when dollarAmount1 - dollarAmount2 = 0 Then 'AmountType3'            
      End As Amounts            
    From
      table1
    Where
      @Date = workDate

END

如果要避免重复代码而导致性能下降,请使用子查询:

select
  location,
  workDate,
  Amounts
from (
    Select 
      location, 
      workDate, 
      case 
        when dollarAmount1 - dollarAmount2 < 0 Then 'AmountType1'
        when dollarAmount1 - dollarAmount2 > 0 Then 'AmountType2'
        when dollarAmount1 - dollarAmount2 = 0 Then 'AmountType3'            
      End As Amounts
    From
      table1
    Where
      @Date = workDate
) foo
where
  Amounts = @AmountType
否则重复代码:

Select 
  location, 
  workDate, 
  case 
    when dollarAmount1 - dollarAmount2 < 0 Then 'AmountType1'
    when dollarAmount1 - dollarAmount2 > 0 Then 'AmountType2'
    when dollarAmount1 - dollarAmount2 = 0 Then 'AmountType3'            
  End As Amounts
From
  table1
Where
  @Date = workDate
  and
  @AmountType = case 
    when dollarAmount1 - dollarAmount2 < 0 Then 'AmountType1'
    when dollarAmount1 - dollarAmount2 > 0 Then 'AmountType2'
    when dollarAmount1 - dollarAmount2 = 0 Then 'AmountType3'            
  End

再说一遍,性能可能根本没有差别。

我使用了子查询。工作起来很有魅力。谢谢