CREATE OR REPLACE FUNCTION "public"."check_idcard"(a_sfz varchar)
RETURNS "pg_catalog"."varchar" AS $BODY$DECLARE
v_sfz varchar;
v_i integer;
v_sum integer;
v_array1 integer[];
v_array2 varchar[];
v_s varchar;
BEGIN
v_sfz:=upper(trim(a_sfz));
if length(v_sfz)=18 then
v_array1:=array[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
v_array2:=array['1','0','X','9','8','7','6','5','4','3','2'];
v_i:=1;
v_sum:=0;
loop
v_s:=substr(v_sfz,v_i,1);
v_sum:=v_sum + cast(v_s as integer)*v_array1[v_i];
v_i:=v_i + 1;
if v_i>17 then
exit;
end if;
end loop;
v_sum:=mod(v_sum,11) + 1;
v_s:=v_array2[v_sum];
if v_s=substr(v_sfz,18,1) then
return 1;
else
return 0;
end if;
else
return -1;
end if;
END
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
使用:
select check_idcard('220183199111111115');
0
select check_idcard('220183199111111116');
1