mysql触发器之姓名转姓名拼音
人员表people 字段:id,peopleNumber,name,namePinyin,sex,birthday,nation。
namePinyin不用填写,根据name自动生成。
wordlib为字库表,内容为文字拼音对照
创建表
create table people( id int auto_increment primary key, peopleNumber varchar(18), name varchar(20), namePinyin varchar(50), sex varchar(4), birthday date, nation varchar(30) )character set utf8;
插入触发器
drop trigger if exists insert_pinyin; delimiter // create trigger insert_pinyin before insert on people for each row begin declare num int default 1; declare single_word varchar(2); declare single_py varchar(10); declare total_py varchar(50) default ''; while num <= char_length(new.name) do set single_word = substr(new.name,num,1); select pinyin into single_py from wordlib where word = single_word; set total_py = concat(total_py,single_py); set num = num + 1; end while; set new.namePinyin = total_py; end // delimiter ;
更新触发器
drop trigger if exists update_pinyin; delimiter // create trigger update_pinyin before update on people for each row begin declare num int default 1; declare single_word varchar(2); declare single_py varchar(10); declare total_py varchar(50) default ''; while num <= char_length(new.name) do set single_word = substr(new.name,num,1); select pinyin into single_py from wordlib where word = single_word; set total_py = concat(total_py,single_py); set num = num + 1; end while; set new.namePinyin = total_py; end // delimiter ; insert into people (name,sex,peopleNumber,birthday,nation) values('张三','男','410306199901010001','19990101','汉族')