-2

Possible Duplicate:
Converting Access Code to SQL

I have an access code using IIF statements that have 2 in 1 and I am trying to rewrite them for SQL as CASE statements but I am hitting some speedbumps.

Sum(IIf([RRDD] Not Like "12*" 
    And [RRDD] Not Like "13*" 
    And [RRDD] Not Like "16*" 
    And [RRDD] Not Like "17*" 
    And [RRDD] Not Like "2706" 
    And [RRDD] Not Like "2707" 
    And [RRDD] Not Like "2331",
    CDbl([2011 Total])*IIf(IsNumeric([Dur_In_Hours]),
    CDbl([Dur_In_Hours]),0),0)) AS SP_DOM_COST

WHere the first IIF is being multiplied by the second IIF is where I am confused, and i need it to be in SQL format

Community
  • 1
  • 1
user1958651
  • 451
  • 1
  • 5
  • 8

2 Answers2

2

You can simplify the logic in both SQL Server and Access. Here is the SQL Server version:

Sum(case when left([RRDD], 2) not in ('12', '13', '16', '17') and
              RRDD not in ('2706', '2707', '2331') and
              isnumeric(dur_in_hours) = 1
         then [2011 Total] * cast(Dur_In_Hours as float)
         else 0.0
    end) AS SP_DOM_COST

In both systems, like is going to incur more overhead than a search through a list of constants. The cast is safe because it is in a where clause (I'm also adding an answer to the reference above, since the answers are not correct).

The replacement for iif is generally case, although this function has been added into SQL Server 2012 (that said, I sort of hope no one uses it).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1
Sum(case when [RRDD] Not Like '12%' 
And [RRDD] Not Like '13%' 
And [RRDD] Not Like '16%' 
And [RRDD] Not Like '17%' 
And [RRDD] Not Like '2706' 
And [RRDD] Not Like '2707' 
And [RRDD] Not Like '2331'
then cast([2011 Total] as float) * 
    case when ISNUMERIC([Dur_In_Hours]) = 1
        then cast([Dur_In_Hours] as float) 
        else 0 
    end
else 0 
end) AS SP_DOM_COST

While IsNUmeric is a valid TSQL function it is apparently not very nice to play with. IF you get odd results check out some other existing answers for workaround. Depending on your data you may be fine though.

Community
  • 1
  • 1
Brad
  • 11,934
  • 4
  • 45
  • 73