18位身份号码是特征组合码,由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位校验码。其含义如下:
(1)对前17位数字本体码加权求和公式为:S = Sum(Ai * Wi), i = 1, ... , 17。其中Ai表示第i位置上的身份证号码数字值,Wi表示第i位置上的加权因子,其各位对应的值依次为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 (2)以11对计算结果取模:Y = mod(S, 11) (3)根据模的值得到对应的校验码,对应关系为: Y值:0 1 2 3 4 5 6 7 8 9 10 校验码:1 0 X 9 8 7 6 5 4 3 2
^[1-9]\d{5}(19|20)\d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2]\d|3[0-1])|(04|06|09|11)(0[1-9]|[1-2]\d|30)|02(0[1-9]|[1-2]\d))\d{3}[\dXx]$
^[1-9]\d{5}(19|20)\d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2]\d|3[0-1])|(04|06|09|11)(0[1-9]|[1-2]\d|30)|02(0[1-9]|1\d|2[0-8]))\d{3}[\dXx]$
说明:
delimiter //
CREATE FUNCTION `fn_checkidcard`(p_idcard varchar(100)) RETURNS varchar(50) CHARSET utf8mb4 DETERMINISTIC
begin
declare v_regstr varchar (200);
declare v_sum int;
declare v_mod int;
declare v_checkcode char(11) default '10x98765432';
declare v_checkbit char(1);
declare v_areacode varchar(200) default '11,12,13,14,15,21,22,23,31,32,33,34,35,36,37,41,42,43,44,45,46,50,51,52,53,54,61,62,63,64,65,71,81,82,91,';
if trim(length(p_idcard)) = 18 then
if instr(v_areacode, concat(substr(p_idcard,1,2),',')) = 0 then
return ('身份证省份码错误');
end if;
if mod(substr(p_idcard,7,4),400) = 0 or (mod(substr(p_idcard,7,4),100) <> 0 and mod(substr(p_idcard,7,4),4) = 0) then
-- 闰年
set v_regstr = '^[1-9]\\d{5}(19|20)\\d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2]\\d|3[0-1])|(04|06|09|11)(0[1-9]|[1-2]\\d|30)|02(0[1-9]|[1-2]\\d))\\d{3}[\\dXx]$';
else
-- 平年
set v_regstr = '^[1-9]\\d{5}(19|20)\\d{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2]\\d|3[0-1])|(04|06|09|11)(0[1-9]|[1-2]\\d|30)|02(0[1-9]|1\\d|2[0-8]))\\d{3}[\\dXx]$';
end if;
if regexp_like(p_idcard, v_regstr) then
-- 求和
set v_sum = (substr(p_idcard, 1, 1) + substr(p_idcard, 11, 1)) * 7
+ (substr(p_idcard, 2, 1) + substr(p_idcard, 12, 1)) * 9
+ (substr(p_idcard, 3, 1) + substr(p_idcard, 13, 1)) * 10
+ (substr(p_idcard, 4, 1) + substr(p_idcard, 14, 1)) * 5
+ (substr(p_idcard, 5, 1) + substr(p_idcard, 15, 1)) * 8
+ (substr(p_idcard, 6, 1) + substr(p_idcard, 16, 1)) * 4
+ (substr(p_idcard, 7, 1) + substr(p_idcard, 17, 1)) * 2
+ substr(p_idcard, 8, 1) * 1
+ substr(p_idcard, 9, 1) * 6
+ substr(p_idcard, 10, 1) * 3;
-- 取模
set v_mod = mod (v_sum, 11);
-- 对应校验位
set v_checkbit = substr(v_checkcode, v_mod + 1, 1);
if v_checkbit = lower(substr(p_idcard, 18, 1)) then
return ('身份证格式验证通过');
else
return ('身份证校验位错误');
end if;
else
return ('身份证格式错误');
end if;
else
return ('身份证号码不是18位');
end if;
end
//
delimiter ;