還是響應公司的業務需求,在做統計表的時候需要對數字進行運算,可是由於前人的偷懶給我造成了很大的麻煩(居然將大寫數字直接存入,沒有阿拉伯數字,暈~);所以啊,我抱怨也沒啥用,而且去網上也沒有找到將中文大寫數字轉換為阿拉伯數字的mysql函數,沒辦法,沒有輪子就只好造輪子啦!
話不多說,上代碼:
CREATE DEFINER = 'root'@'localhost'
FUNCTION myhouse.change_to_num(cn_num varchar(255))
RETURNS int(11)
begin
declare i int default 1;
declare result int default 0;
declare str varchar(10);
declare num int;
declare temp int default 1;
while i <= char_length(cn_num) do
set str = substring(cn_num, i, 1);
set num = case str
when '零' then 0
when '壹' then 1
when '貳' then 2
when '叄' then 3
when '肆' then 4
when '伍' then 5
when '陸' then 6
when '柒' then 7
when '捌' then 8
when '玖' then 9
when '拾' then 10
when '佰' then 100
when '仟' then 1000
ELSE 0
end;
if num!=10 && num!=100 && num!=1000 then
set temp = num;
IF i=char_length(cn_num) THEN
SET result = result + temp;
END IF;
else
set result = result + (temp * num);
end if;
set i = i + 1;
end while;
return result;
end
我這個不能保證適用於所有轉換,而且可能還有隱藏bug。。。因此僅供參考哈