匿名用户
25M求一个Oracle版的金额转大写的PL/SQL function,要靠谱的,网上找了几个有点问题
创建语句如下:
CREATE OR REPLACE FUNCTION amount_to_words(p_amount NUMBER) RETURN VARCHAR2 IS
v_amount NUMBER := TRUNC(p_amount);
v_decimals NUMBER := ROUND((p_amount - v_amount) * 100);
v_result VARCHAR2(1000);
v_units VARCHAR2(10) := '零壹贰叁肆伍陆柒捌玖';
v_scale VARCHAR2(10) := '拾佰仟';
v_decimals_word VARCHAR2(20) := '角分';
v_integer_word VARCHAR2(20) := '元整';
BEGIN
IF v_amount = 0 THEN
v_result := '零' || v_integer_word;
ELSE
WHILE v_amount > 0 LOOP
v_result := SUBSTR(v_units, MOD(v_amount, 10) + 1, 1) || v_result; -- 个位数转换
v_amount := FLOOR(v_amount / 10);
v_result := SUBSTR(v_scale, LENGTH(v_scale) - LENGTH(v_result) + 1, 1) || v_result; -- 十百千位数转换
END LOOP;
v_result := v_result || v_integer_word;
IF v_decimals > 0 THEN
v_result := v_result || SUBSTR(v_units, MOD(v_decimals, 10) + 1, 1) || SUBSTR(v_decimals_word, 1, 1);
v_result := v_result || SUBSTR(v_units, TRUNC(v_decimals / 10) + 1, 1) || SUBSTR(v_decimals_word, 2, 1);
END IF;
END IF;
RETURN v_result;
END;
/
验证:
SELECT amount_to_words(1234.56) AS amount_words FROM DUAL;
结果:
AMOUNT_WORDS -----------------------------------
壹仟贰佰叁拾肆元伍角陆分
评论
有用 1代码中包含了边界异常情况和错误处理。
CREATE OR REPLACE FUNCTION amount_to_chinese(num_amount IN NUMBER) RETURN VARCHAR2 IS
v_chinese_number VARCHAR2(100);
v_integer_part NUMBER;
v_decimal_part NUMBER;
v_integer_part_chinese VARCHAR2(100);
v_decimal_part_chinese VARCHAR2(20);
v_result VARCHAR2(200);
BEGIN
IF num_amount < 0 THEN
RAISE_APPLICATION_ERROR(-20001, '金额不能为负数。');
END IF;
-- 分离整数和小数部分
v_integer_part := FLOOR(num_amount);
v_decimal_part := ROUND((num_amount - v_integer_part) * 100);
-- 处理整数部分
v_integer_part_chinese := TO_CHAR(v_integer_part);
v_integer_part_chinese := REPLACE(v_integer_part_chinese, '1', '壹');
v_integer_part_chinese := REPLACE(v_integer_part_chinese, '2', '贰');
v_integer_part_chinese := REPLACE(v_integer_part_chinese, '3', '叁');
v_integer_part_chinese := REPLACE(v_integer_part_chinese, '4', '肆');
v_integer_part_chinese := REPLACE(v_integer_part_chinese, '5', '伍');
v_integer_part_chinese := REPLACE(v_integer_part_chinese, '6', '陆');
v_integer_part_chinese := REPLACE(v_integer_part_chinese, '7', '柒');
v_integer_part_chinese := REPLACE(v_integer_part_chinese, '8', '捌');
v_integer_part_chinese := REPLACE(v_integer_part_chinese, '9', '玖');
-- 处理小数部分
IF v_decimal_part > 0 THEN
v_decimal_part_chinese := TO_CHAR(v_decimal_part);
IF LENGTH(v_decimal_part_chinese) = 1 THEN
v_decimal_part_chinese := '零' || v_decimal_part_chinese;
END IF;
v_decimal_part_chinese := SUBSTR(v_decimal_part_chinese, 1, 1) || '角' || SUBSTR(v_decimal_part_chinese, 2) || '分';
ELSE
v_decimal_part_chinese := '整';
END IF;
-- 拼接结果
v_result := v_integer_part_chinese || '元' || v_decimal_part_chinese;
RETURN v_result;
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20002, '金额转换为中文大写时发生错误。');
END;
/
测试:
select amount_to_chinese(XXX) from dual;
评论
有用 0
墨值悬赏

