Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql procedure IF number is odd or even

My learning mysql and my question is to check what i'm doing wrong here:

I'm trying to make a sql procedure to check if the first number of a number user enters is odd or even but im getting syntax error in line 9 near ';//'

Here's the sql:

MYSQL>
DELIMITER //

CREATE PROCEDURE num()
BEGIN
IF (SELECT LEFT(num,1))=1 OR (SELECT LEFT(num,1))=3 OR (SELECT LEFT(num,1))=5 OR (SELECT LEFT(num,1))=7 THEN
SELECT 'number is odd';
ELSEIF (SELECT LEFT(num,1))=2 OR (SELECT LEFT(num,1))=4 OR (SELECT LEFT(num,1))=6 OR (SELECT LEFT(num,1))=8 THEN
SELECT 'number is even'; 
END IF;

END;//

And here is the CALL of then number for testing:

MYSQL> CALL num(3123123123) 

Any ideas?

like image 578
User_T Avatar asked Dec 11 '14 20:12

User_T


People also ask

How do you check if a number is odd or even in MySQL?

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

How do you check if a number is odd?

If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd.


1 Answers

what you want to do is a calculation. % 2 will give the remainder of a division by 2. if that remainder is not 0 then it is odd

SELECT IF(LEFT(num, 1) % 2 <> 0, "number is odd", "number is even")

you also want to fix your procedure to something like this

DELIMITER //
CREATE PROCEDURE `num`( IN input_num int, OUT output varchar(200))
    BEGIN
        SELECT IF(LEFT(input_num, 1) % 2 <> 0, "number is odd", "number is even") INTO output;
    END//

you would call it like this.

set @a = '';
call num(333, @a);

select @a;

demo fiddle

like image 128
John Ruddell Avatar answered Sep 24 '22 00:09

John Ruddell