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?
10 Answers Use the modulus operator n % 2 . It returns 0 if the number is even, and 1 if the 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With