首先我们来看看验证规则:
从第一位到第十七位的系数分别为: 7-9-10-5-8-4-2-1-6-3-7-9-10-5-8-4-2
接下来将这17位数字和系数相乘的结果相加,然后用加出来和除以11,看余数,余数只可能有 0-1-2-3-4-5-6-7-8-9-10 这11个数字。其分别对应的最后一位身份证的号码为1-0-X -9-8-7-6-5-4-3-2。
注意:该验证方法仅针对18位身份证。
创建一个存储过程,代码如下:
creater proc sfzjy
@sfzh varchar(18) --身份证号码
as
begin
declare @i int --循环变量
declare @sum int --位数与系数之和
declare @xs varchar(17) --将固定系数存为字符串
set @sum=0
set @xs='79a584216379a5842'--当系数为10时转换为a
set @i=1
while (@i<=17)
begin
set @sum= cast(substring(@sfzh,@i,1) as int)*( ( case when substring(@xs,@i,1)='a' then 10 else cast (SUBSTRING(@xs,@i,1) as int) end) )+@sum
set @i=@i+1
end
declare @ys int --余数
set @ys= @sum%11
declare @jym varchar(4) --校验码
set @jym= case when @ys=0 then '1'
when @ys=1 then '0'
when @ys=2 then 'X'
when @ys=3 then '9'
when @ys=4 then '8'
when @ys=5 then '7'
when @ys=6 then '6'
when @ys=7 then '5'
when @ys=8 then '4'
when @ys=9 then '3'
when @ys=10 then '2' end
if(@jym=right(@sfzh,1)) --对比校验码与身份证最后一位数是否相等
return 1
else
return 0
end
注意:在调用存储过程,传入身份证参数时,注意对身份证字段进行处理,左右去空,限制身份证号码为18位。