MySQL 創建函數, MySQL定義函數實現漢字轉拼音 MySQL漢字轉拼音
一、MySQL創建函數
1、語法
CREATE FUNCTION fun_name([paramName type , paramName type]) RETURNS type
BEGIN
-- do something
RETURN type;
END
- fun_name: 函數名稱,自定義 ,不可重複。
- paramName type:參數名稱、參數類型 , 可選,非必填項。
- RETURNS type :返回值類型,必填的。
2、創建函數
CREATE FUNCTION fun_one(arg1 int , arg2 VARCHAR(100)) RETURNS VARCHAR(100)
BEGIN
-- do something
RETURN NOW();
END
3、調用函數
SELECT fun_one(1,'a');
4、刪除函數
DROP FUNCTION IF EXISTS fun_one ;
5、查看函數
SHOW FUNCTION STATUS [WHERE db = 'xxxx''];
二、MySQL漢字轉拼音
1、需要一個拼音--漢字 對應的字庫。 pinyin_data 表,內如如下:
2、創建 chinese_to_pinyin()函數,實現漢字轉換爲拼音,代碼如下:
DROP FUNCTION IF EXISTS chinese_to_pinyin ;
CREATE FUNCTION chinese_to_pinyin(str varchar(100) charset gbk) RETURNS VARCHAR(200)
BEGIN
DECLARE result varchar(200) charset gbk DEFAULT '' ;-- 最終結果
DECLARE length int DEFAULT 0 ; -- 字符串的長度
DECLARE default_index int DEFAULT 1 ; -- 默認截取字符串的位置
DECLARE judge_index int DEFAULT 0 ; -- 判斷非漢字字符位置,空格,逗號等
DECLARE str_char VARCHAR(4) DEFAULT '' ; -- 截取的單個字符
DECLARE pinyin_str VARCHAR(30) DEFAULT null ; -- 轉換後的拼音字符串
SET length = CHAR_LENGTH(str); -- 計算傳入字符串長度
-- 執行 while 循環進行判斷
WHILE default_index <= length DO
SET str_char = SUBSTRING(str ,default_index ,1);
SET pinyin_str = NULL;
SELECT pinyin INTO pinyin_str FROM pinyin_data WHERE hanzi = str_char ; -- 漢字轉換爲拼音字符串
SET pinyin_str = IFNULL(pinyin_str,str_char);
-- 判斷","逗號情況
SET judge_index = POSITION(',' IN pinyin_str);
IF (judge_index >= 1) THEN
SET pinyin_str = LEFT(pinyin_str , judge_index-1);
END IF;
-- 判斷空格情況
SET judge_index = POSITION(' ' IN str_char);
IF (judge_index >= 1) THEN
SET pinyin_str = LEFT(pinyin_str , judge_index - 1);
END IF ;
SET result = CONCAT(result,pinyin_str);
SET default_index = default_index + 1 ;
END WHILE ;
RETURN LOWER(result) ;
END
3、測試效果如下:
a. SELECT chinese_to_pinyin('中華');
b. SELECT chinese_to_pinyin('中 華');
c. SELECT chinese_to_pinyin('中 ,華');
三、總結
1、MySQL 創建函數,和存儲過程差不多。區別:存儲過程可以沒有返回值,也可以有1個或多個返回值。 函數必須有返回值,僅僅只有1個。 (不知道這樣總結是否正確?)
2、漢字轉換爲拼音,常用於根據名字生成用戶名,登錄名等。
3、pinyin_data 表數據太多,有2萬多條,需要的可以私信,謝謝。
參考資料:
MyBatis調用存儲過程,MyBatis調用函數的使用方法