0

パラメータを追加したいプロシージャがあります-パラメータはと呼ばれ@AmountTypeます。@AmountType次に、そのパラメーターをwhere句に追加して、さまざまな金額タイプをフィルター処理できるようにします。@AmountTypeトリッキーな部分は、selectの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 に答える