欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

mysql生成身份證號

林子帆2年前12瀏覽0評論

MySQL是一款流行的開源數據庫管理系統,其在數據處理和存儲方面表現出色。在數據庫中生成身份證號是常見的需求之一,下面介紹如何在MySQL中生成身份證號。

CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`gender` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0未知 1男 2女',
`birth` date NOT NULL DEFAULT '1970-01-01',
`address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`id_card` varchar(18) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '身份證號碼',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

以上代碼創建了一個名為“person”的表,包含了id、name、gender、birth、address和id_card字段,其中id是自增主鍵。在該表中生成身份證號,需要將身份證前17位按照身份證號的規則生成,最后一位為校驗碼。下面是生成身份證號的代碼:

DELIMITER //
CREATE PROCEDURE generate_id_card(inout person_id int)  
BEGIN  
DECLARE base CHAR(17) DEFAULT '0123456789';  
DECLARE gender INT DEFAULT 0;  
DECLARE year INT DEFAULT 0;  
DECLARE month INT DEFAULT 0;  
DECLARE day INT DEFAULT 0;  
DECLARE area_code CHAR(6) DEFAULT '510101';  
DECLARE random CHAR(2) DEFAULT '00';  
DECLARE sum INT DEFAULT 0;  
DECLARE s CHAR(1) DEFAULT '';  
DECLARE odd CHAR(1) DEFAULT '';  
DECLARE select_random INT DEFAULT 0;  
SELECT gender FROM person WHERE id = person_id INTO gender;  
SELECT year(birth) FROM person WHERE id = person_id INTO year;  
SELECT month(birth) FROM person WHERE id = person_id INTO month;  
SELECT day(birth) FROM person WHERE id = person_id INTO day;  
# 選擇最后兩位
select ROUND(RAND()*(99-10)+10) into select_random; 
SET random = select_random; 
# 選擇區域代碼
select ROUND(RAND()*(59-10)+10) into select_random; 
SET area_code = CONV(select_random,10,16);  
SET base = CONCAT(area_code, year, LPAD(month, 2, 0), LPAD(day, 2, 0));  
# 循環計算校驗碼
SET sum = 0;  
SET s = '';  
SET odd = '';  
FOR i IN 1..16 DO  
SET s = SUBSTRING(base, i, 1);  
IF i % 2 = 0 THEN  
SET sum = sum + (SUBSTRING(base, i, 1) * 2) % 10 + FLOOR((SUBSTRING(base, i, 1) * 2) / 10);  
ELSE  
SET sum = sum + SUBSTRING(base, i, 1);  
END IF;  
END FOR;  
SET odd = CHAR((10 - sum % 10) % 10 + 48);  
SET base = CONCAT(base, odd, random);  
UPDATE person SET id_card = base WHERE id = person_id;  
END;
//
DELIMITER ;

以上代碼創建了一個名為“generate_id_card”的存儲過程,傳入參數為person_id,表示要生成身份證號的記錄的id。在該存儲過程中,首先通過傳入參數獲取該條記錄的gender、birth等信息,然后隨機選擇最后兩位和區域代碼,最后循環計算校驗碼,生成完整的身份證號,并更新到數據庫。

使用以上代碼,在MySQL中可以方便地生成身份證號。