MySql 存储过程 将15位身份证号转化为18位返回

DROP PROCEDURE IF EXISTS get18Id;
/*

功能名称:  将15位身份证号转化为18位返回,非15位身份证号原值返回

作者:InJavaWeTrust

日期:2016/02/25

  参数             IN/OUT     类型                                 说明

 identityCard      IN        VARCHAR                             15位身份证号
 retIc             OUT       VARCHAR                             18位身份证号

*/
CREATE PROCEDURE get18Id(IN identityCard VARCHAR(15), OUT retIc VARCHAR(18))
BEGIN
	DECLARE id17 VARCHAR(17);
	DECLARE id18 VARCHAR(18);
	DECLARE v_sum INT;
	DECLARE v_y INT;
	DECLARE v_i INT;
	-- 定义数组存放加权因子(weight factor)
	SET @wf = "7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2";
	-- 定义数组存放校验码(check code)
	SET @cc = "1,0,X,9,8,7,6,5,4,3,2";
	SET v_sum = 0;
	SET v_y   = 0;
	SET v_i   = 1;

	-- 判断传入id长度
	IF CHAR_LENGTH(identityCard) <> 15 THEN
		SET retIc = identityCard;
	ELSE
		-- 加上两位年'19'
		SET id17 = CONCAT(CONCAT(SUBSTRING(identityCard,1,6),'19'), SUBSTRING(identityCard,7));
    -- 十七位数字本体码加权求和
		WHILE v_i <= 17 DO
			SET v_sum = v_sum + CAST(SUBSTRING(id17,v_i,1) AS INT) * CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(@wf,',',v_i),",",-1) AS INT);
			SET v_i = v_i + 1;
		END WHILE;
		-- 计算模
		SET v_y = MOD(v_sum,11);
		-- 17位数字 + 通过模得到对应的校验码
		SET id18 = CONCAT(id17,SUBSTRING_INDEX(SUBSTRING_INDEX(@cc,",",v_y + 1),",",-1));

		SET retIc = id18;

	END IF;	
	
END;

CALL get18Id("511702800222130",@id18);
select @id18; 

 

你可能感兴趣的:(mysql,存储过程,数组)