用SQL将数字转换为中文数字


IF OBJECT_ID('fn_GetChnNum') IS NOT NULL
BEGIN
DROP FUNCTION dbo.fn_GetChnNum;
END;
GO
CREATE FUNCTION fn_GetChnNum ( @Number AS BIGINT )
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE @ChnNum VARCHAR(100);
IF LEN(@Number) = 1
BEGIN
SET @ChnNum = SUBSTRING('零一二三四五六七八九', @Number + 1, 1);
END;
ELSE
BEGIN
DECLARE @Len INTEGER;
DECLARE @strNum AS VARCHAR(100);
DECLARE @i AS INTEGER;
DECLARE @NumWs AS INTEGER;
DECLARE @Unit AS VARCHAR(10);

SET @ChnNum = '';

SET @strNum = CAST(@Number AS VARCHAR(100));
SELECT @Len = LEN(@strNum);
SET @i = 1;

WHILE @i <= @Len
BEGIN
SET @Unit = '';
SET @NumWs = @Len + 1 - @i;
IF @NumWs > 1
BEGIN
SET @Unit = CASE WHEN @NumWs % 4 = 0 THEN '千'
WHEN @NumWs % 2 = 0 THEN '十'
WHEN @NumWs % 8 = 1 THEN '亿'
WHEN @NumWs % 4 = 1 THEN '万'
WHEN @NumWs % 2 = 1 THEN '百'
ELSE ''
END;
END;


SET @ChnNum = @ChnNum
+ dbo.fn_GetChnNum(SUBSTRING(@strNum, @i, 1));

SET @ChnNum = @ChnNum + @Unit;

SET @i = @i + 1;
END;
IF CHARINDEX('零元', @ChnNum) <> 0
SET @ChnNum = REPLACE(@ChnNum, '零元', '元');
IF CHARINDEX('零万', @ChnNum) <> 0
SET @ChnNum = REPLACE(@ChnNum, '零万', '万');
IF CHARINDEX('零亿', @ChnNum) <> 0
SET @ChnNum = REPLACE(@ChnNum, '零亿', '亿');
IF CHARINDEX('零百', @ChnNum) <> 0
SET @ChnNum = REPLACE(@ChnNum, '零百', '零');
IF CHARINDEX('零千', @ChnNum) <> 0
SET @ChnNum = REPLACE(@ChnNum, '零千', '零');
RETURN @ChnNum;
END;

RETURN @ChnNum;
END;

GO

--测试
SELECT dbo.fn_GetChnNum(203423124);



用SQL将数字转换为中文数字

相关推荐