Odd or even numbers

  • Hi there,

    I am trying to use SQL to determine whether a value field is an odd or even number. I tried the following:

    Case

  • You can take the value and MOD by 2.

    select x.i, case x.i % 2 when 0 then 'even' when 1 then 'odd' end

    from

         ( select 1 as i union all

     select 2 union all

     select 3 union all

     select 4 union all

     select 5

         )  x

    i               

    ----------- ----

    1           odd

    2           even

    3           odd

    4           even

    5           odd

    (5 row(s) affected)

    /Kenneth

  • Something like this

    DECLARE @i INT

    SET @i = 1

    WHILE @i < 20

    BEGIN

     SELECT @i,

      CASE @i % 2

       WHEN 0 THEN 'Even'

       ELSE 'Odd'

      END AS OddOrEven

     SET @i = @i+1

    END

     

  • thanks guys - exactly what I need!

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

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