2012-04-13 27 views
0

我有一个proc,我想添加一个参数 - 参数将被称为@AmountType。然后,我想将@AmountType参数添加到我的where子句中,以便我可以筛选不同的数量类型。棘手的部分是,我希望@AmountType的值是我选择的case语句部分的结果。
因此,只显示AmountType1记录,或者只显示AmountType2记录等等。显然,我不能仅仅执行where @AmountType = Amounts,因为Amounts不是真正的列。从选择Case语句在Where子句中使用结果字段

有关如何完成此任务的任何想法?

这是我的发言:

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 

回答

0

如果你想避免在可能引起性能下降的expence重复的代码,然后使用子查询:

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 

然后再次,性能可能没有任何差异。

+0

我使用了子查询。奇迹般有效。谢谢! – SeanFlynn 2012-04-13 17:40:07