2012-04-13 3 views
0

매개 변수를 추가하려는 proc가 있습니다 - 매개 변수는 @AmountType이라고합니다. 그런 다음 where 절에 @AmountType 매개 변수를 추가하여 다른 금액 유형을 필터링 할 수 있습니다. 까다로운 부분은 @AmountType의 값을 내 선택의 case 문 부분의 결과로 바꾸기를 원한다는 것입니다.
그래서 AmountType1 레코드 만 표시하거나 AmountType2 레코드 만 표시합니다. where @AmountType = Amounts은 분명히 할 수 없습니다. Amounts은 실제 열이 아니기 때문에 가능합니다.Where 절의 Select Case 문에서 결과 필드 사용

이 작업을 수행하는 방법에 대한 아이디어가 있으십니까? 당신은 가능한 성능 저하의 expence에서 중복 코드를 방지하려면

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

, 다음 하위 쿼리 사용 :

내 문입니다

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