判断身份证号是否合法
-- =============================================
-- Description: <判断身份证号是否合法,返回结果对应如下:>
-- -2:含有非法字符
-- -1:位数不正确(不为15或18位)
-- 0:位数正确,但证号不合法
-- 1:位数正确,且证号合法
-- =============================================
create FUNCTION [dbo].[f_checksfzh]
(
@ID varchar(30) --要校验的证号
)
RETURNS int
AS
BEGIN
DECLARE @ID15 varchar(30),@S18 int,@check char,@result int
if len(@ID)<>18 and len(@ID)<>15
set @result = -1 --位数不正确
else if len(@ID)=15
begin
if ISNUMERIC(@ID)=1
set @result = 1
else
set @result = -2 --含有非法字符
end
else --18位
begin
if ISNUMERIC(left(@ID,17))<>1 or (upper(right(@ID,1))<>'X' and ISNUMERIC(right(@ID,1))<>1)
set @result = -2 --含有非法字符
else
begin
set @ID15 = left(@ID,6)+substring(@ID,9,len(@ID) -9 )
SET @S18 = ( (SUBSTRING(@ID15,1,1)*7) + (SUBSTRING(@ID15,2,1)*9) + (SUBSTRING(@ID15,3,1)*10)
+ (SUBSTRING(@ID15,4,1)*5) + (SUBSTRING(@ID15,5,1)*8) + (SUBSTRING(@ID15,6,1)*4) + (1*2) + (9*1)
+ (SUBSTRING(@ID15,7,1)*6) + (SUBSTRING(@ID15,8,1)*3) + (SUBSTRING(@ID15,9,1)*7)
+ (SUBSTRING(@ID15,10,1)*9)+ (SUBSTRING(@ID15,11,1)*10)+ (SUBSTRING(@ID15,12,1)*5)
+ (SUBSTRING(@ID15,13,1)*8) +(SUBSTRING(@ID15,14,1)*4) + (SUBSTRING(@ID15,15,1)*2) ) % 11
if @S18 = 0 set @check='1'
if @S18 = 1 set @check='0'
if @S18 = 2 set @check='X'
if @S18 = 3 set @check='9'
if @S18 = 4 set @check='8'
if @S18 = 5 set @check='7'
if @S18 = 6 set @check='6'
if @S18 = 7 set @check='5'
if @S18 = 8 set @check='4'
if @S18 = 9 set @check='3'
if @S18 = 10 set @check='2'
if @check=right(upper(@ID),1) set @result=1
else set @result=0
END
end
RETURN @result
END