USE [xd]
GO
/****** Object: UserDefinedFunction [dbo].[sfz15to18] Script Date: 04/24/2013 16:41:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER function [dbo].[sfz15to18](@idtfin varchar(18))--转换身份证号
returns varchar(18) --输出号码
as
begin
declare @errtcd int,@prrtcd int,@idtfou varchar(18)
--exec kn_pc_reg 'kn_cs_convertidtfno'
declare @retval int
declare @idtf17 varchar(18), --中间17位处理变量
@loopvl int,--循环变量
@smryvl int --校验位和
--将输入身份证赋给中间处理变量
select @idtf17 = rtrim(ltrim(@idtfin))
--身份证长度合法性校验
if len(@idtf17) not in (15, 17, 18)
begin
select @idtfou = @idtfin
select @retval = -1
select @idtfou = '身份证长度不正确'
end
--转化为十七位身份证(没有校验位)
select @idtf17 = case len(@idtf17)
when 15 then
substring(@idtf17, 1, 6) + '19' + substring(@idtf17, 7, 9)
when 18 then
substring( @idtf17 ,1, 17)
else @idtf17
end
--计算校验位数值
select @loopvl = 17, @smryvl = 0
while @loopvl > 0
begin
--非数字字符的合法性校验
if ascii(substring(@idtf17, @loopvl, 1)) < 48 or ascii(substring(@idtf17, @loopvl, 1) ) >57
begin
select @idtfou = @idtfin
select @retval = -2
select @idtfou = '身份证号码不合法'
end
select @smryvl = @smryvl + convert(int,substring(@idtf17, @loopvl, 1)) *
(case (19 - @loopvl)
when 1 then 1 when 2 then 2 when 3 then 4
when 4 then 8 when 5 then 5 when 6 then 10
when 7 then 9 when 8 then 7 when 9 then 3
when 10 then 6 when 11 then 1 when 12 then 2
when 13 then 4 when 14 then 8 when 15 then 5
when 16 then 10 when 17 then 9 when 18 then 7
end)
select @loopvl = @loopvl - 1
end
--生成最终号码
select @idtfou = @idtf17 + case @smryvl % 11
when 0 then '1' when 1 then '0' when 2 then 'X' when 3 then '9'
when 4 then '8' when 5 then '7' when 6 then '6' when 7 then '5'
when 8 then '4' when 9 then '3' when 10 then '2' end
return @idtfou
end