0

我有一个 proc,我想向其中添加一个参数 - 将调用该参数@AmountType。然后我想将该@AmountType参数添加到我的where子句中,以便过滤不同的金额类型。棘手的部分是我希望值是@AmountType我选择的 case 语句部分的任何结果。
所以,只显示 AmountType1 记录,或者只显示 AmountType2 记录等。显然,我不能这样做,where @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
4

1 回答 1

0

如果您想以可能的性能下降为代价避免重复代码,请使用子查询:

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

话又说回来,性能可能根本没有区别。

于 2012-04-13T16:59:17.760 回答