tags:

views:

221

answers:

4

hi guys

Bit rusty on the old sql.

Can you help?

Given a number eg 1 or 2 or 4 I need to determine if it's even or odd number and do some calculation depending if even or odd .

How do you detect that in sql (sql server 2000) thanks a lot

+9  A: 

Use the modulus operator n % 2. It returns 0 if the number is even, and 1 if the number is odd.

Mark Byers
Do you do something likeDeclare @myNumber intset @myNumber=1 if Select (@myNumber% 2)=1 print 'even' else print 'odd'
jo
Yes, or if you want to do it inside a select, use the "case ... when ... then" construct.
Mark Byers
I see that you haven't accepted an answer yet. Do you need more help with this?
Mark Byers
+2  A: 

Use the modulus operator (%).

x % 2

will tell you if x is even or odd.

Artelius
+3  A: 

You can also use sql server BIT WISE operators

DECLARE @Int INT

SELECT @Int = 103

SELECT @Int & 1, @Int % 2
astander
jo
Try thisdeclare @myNumber int ,@result intset @myNumber = 16 select Result = (case when @myNumber % 2 = 0 then @myNumber * 1 else @myNumber * 2 end) %10
priyanka.sarkar
priyanka.sarkar
A: 

declare @t table(num int) insert into @t select 1 union all select 2 union all select 3 union all select 4

select 
    num
    ,case when num % 2 = 0 then 'Even' else 'Odd' end as Status
from @t

Output:

num Status

1   Odd
2   Even
3   Odd
4   Even

e.g. If the number is even(multiply by 1) or odd (multiply by 2) then divide by 10 and get the remainder

declare @myNumber int ,@result int
set @myNumber = 16 
select  
    Result = 
    (case when @myNumber % 2 = 0 then @myNumber * 1 else @myNumber * 2 end) %10

Result

6

when @myNumber = 11 then

Result

2

Hope this helps

priyanka.sarkar