2012-04-13 21 views
0

私はパラメータを追加したいprocを持っています - パラメータは@AmountTypeと呼ばれます。私はwhere句に@AmountTypeパラメータを追加したいので、さまざまな金額のタイプをフィルタリングすることができます。面倒なところは、@AmountTypeという値を、私が選択したcase文の部分の結果とすることです。
したがって、AmountType1レコードのみを表示するか、AmountType2レコードのみを表示します。where @AmountType = Amountsは明らかに実行できません。Amountsは実際の列ではないためです。結果欄をWhere句のSelect Case文から使用

どのようにこれを達成するためのアイデアですか?

これは私の文です:

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

関連する問題