简体   繁体   中英

MySQL procedure, female or male based on identification number

I would like to determine based on identification code if a person is a male or female. Identification code is int(11) and first number of that specifies if it is male or female. So for example code beginning with 2, 4, 6 and 8 are females and 1, 3, 5 and 7 are males. What I have now (parameter is in_ik int(11):

BEGIN

DECLARE s VARCHAR(20) DEFAULT '';

IF LEFT(in_ik, 1) % 2 = 0 THEN
    SET s = "female";
ELSEIF LEFT(in_ik, 1) % 2 != 0 THEN
    SET s = "Male";
ELSE
    SET s = "Other";
END IF;
SELECT s;

END

When I test the procedure, it says everytime that it is female. procedure code

Not really surpising that this fails when passed an 11 digit number ,see https://dev.mysql.com/doc/refman/8.0/en/integer-types.html for maximum sizes for integers (btw (11) means max display size is 11 not store as 11 digit integer) I suggest you change in_ik to big int. In fact I get an error when I try to run this code as is..

If you check for pair (female) and odd (male ) you could use directly MOD() (or integer division %) instead of left 1 (left is for string not for integer )

BEGIN

DECLARE s VARCHAR(20) DEFAULT '';

IF MOD(in_ik, 2)= 0 THEN
    SET s = "female";
ELSE
    SET s = "Other";
END IF;
SELECT s;

END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM