遇到的问题:
遇到一个数据统计的需求,要求,统计身份证号码性别位填写错误的个数。
首先普及身份证性别位:
至今为止身份证有18位和15位两种。18位身份证号性别位是17位,第17位数字奇数为男性,偶数为女性,0也是女性。15位身份证号性别位是最后一位,第15位数字为奇数是男性,偶数是女性,0和X 也是女性,X必须是大写。
因为想简化统计sql,让人更容易阅读,也为了好书写,就将身份证号性别位的判别写到了函数中即自定义了一个函数。
定义函数格式:
create or replace function F_SFZXB_DM(param_name in | out | in out param_type) return result_tpye is
– 声明 变量部分
begin
– 逻辑部分
end F_SFZXB_DM;
注意需要 函数传参方式有 in 、out 、in out 3种 和过程用法一致
异常处理:
create or replace function…
…
begin
exception
when others then
–写你想要做的事
end;
我的代码:
create or replace function F_SFZXB_DM(sfzhm in varchar2) return number is
begin
– 身份证性别 校验
–18位 身份证号 奇数 男 偶数 0 女
if length(sfzhm) = 18 then
– 首先判断 性别位 是否正确
if not REGEXP_LIKE(substr(sfzhm,-2,1),’[0-9]|X’) then
return 3;– 返回3的就是错误数据
elsif mod(substr(sfzhm,-2,1),2) = 0 then
return 2;– 性别女 性别代码
elsif mod(substr(sfzhm,-2,1),2) = 1 then
return 1;– 性别男 性别代码
end if;
– 15位 身份证号 奇数 男 偶数 0 X 女
elsif length(sfzhm) = 15 then
– 首先判断 性别位 是否正确
if not REGEXP_LIKE(substr(sfzhm,-1),’[0-9]|X’) then
return 3;– 返回3的就是错误数据
elsif substr(sfzhm,-1) = ‘X’ then
return 2;– 性别女 性别代码
elsif mod(substr(sfzhm,-1),2) = 0 then
return 2;– 性别女 性别代码
elsif mod(substr(sfzhm,-1),2) = 1 then
return 1;– 性别男 性别代码
end if;
end if;
end F_SFZXB_DM;