Case Vs IF Else

  • Hi,

    In one of my project I am using both case as well as if else statement the condition and required output variables are same but I am getting different values.

    Ex:

    declare @l decimal(38,2)

    set @l = 24.35

    if @l - convert(int,@l) = 0

    begin

    select floor (@l)

    end

    else

    begin

    select @l

    end

    select

    case

    when @l - convert(int, @l) = 0

    then floor (@l)

    else @l

    end

    Can anyone explain the logic behind this?

  • I can't speak for others but in many cases they are interchangeable. In cases where a set if being evaluated only a CASE statement can be used, in cases where you are operating on ONLY one set of values a CASE OR IF can be. The example you showed is an example of the later case.

    Clear?

    CEWII

  • In the select statement with the CASE function, there is an implicit conversion of the decimal value (variable @l) to INT. This is due to the floor() function returning an integer value.

  • Use the acos instead of that return float so implicit conversion can not be a question.

    declare @l decimal(38,2)

    SET @l = 24.35

    -----Right Result---------

    if (@l - convert(int,@l)) = 0

    begin

    SELECT

    FLOOR(@l)

    end

    else

    begin

    SELECT

    @l

    end

    ------------Wrong Result-----------

    SELECT

    CASE

    WHEN @l - convert(int,@l) = 0 THEN ACOS (@l)

    ELSE @l

    --ELSE 'Maulin'

    END

    Select CAST(@l - CONVERT(int, @l) AS decimal(38,2))

    Select cast(0 AS decimal(38,2))

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply