SQL标量值函数:小写金额转大写

我们日常开发业务系统中,作为统计报表中,特别是财务报表,显示中文金额经常遇到。

转换大小写的方法有很多,以下是从数据库函数方面解决这一问题.

效果如图:

调用:SELECT dbo.[Fn_ConvertRMB](192.4)

image

具体函数如下:

-- =============================================
-- 调用:SELECT dbo.[Fn_ConvertRMB](192.4)
-- Create date: 2015-01-06
-- Description:    返回中文金额
-- =============================================
CREATE FUNCTION [dbo].[Fn_ConvertRMB] (@num NUMERIC(14, 2))
RETURNS VARCHAR(100)
AS
    BEGIN
        DECLARE @n_data VARCHAR(20) ,
            @c_data VARCHAR(100) ,
            @n_str VARCHAR(10) ,
            @i INT
        SET @n_data=RIGHT(SPACE(14)+CAST(CAST(ABS(@num*100) AS BIGINT) AS VARCHAR(20)), 14)
        SET @c_data=''
        SET @i=1
        WHILE @i<=14
            BEGIN
                SET @n_str=SUBSTRING(@n_data, @i, 1)
                IF @n_str<>' '
                    BEGIN
                        IF NOT ((SUBSTRING(@n_data, @i, 2)='00')
                            OR ((@n_str='0')
                            AND ((@i=4)
                            OR (@i=8)
                            OR (@i=12)
                            OR (@i=14))))
                            SET @c_data=@c_data+SUBSTRING('零壹贰叁肆伍陆柒捌玖', CAST(@n_str AS INT)+1, 1)
                        IF NOT ((@n_str='0')
                            AND (@i<>4)
                            AND (@i<>8)
                            AND (@i<>12))
                            SET @c_data=@c_data+SUBSTRING('仟佰拾亿仟佰拾万仟佰拾圆角分', @i, 1)
                        IF SUBSTRING(@c_data, LEN(@c_data)-1, 2)='亿万'
                            SET @c_data=SUBSTRING(@c_data, 1, LEN(@c_data)-1)
                    END
                SET @i=@i+1
            END
        IF @num<0
            SET @c_data='(负数)'+@c_data
        IF @num=0
            SET @c_data='零圆'
        IF @n_str='0'
            SET @c_data=@c_data+'整'
        RETURN(@c_data)
    END

posted on 2020-09-07 11:27  wwwlzp  阅读(412)  评论(0编辑  收藏  举报

导航