- ALTER FUNCTION GetCNDay
- (
- @dt
- )
- RETURNS Nvarchar(50)
- AS
- BEGIN
- DECLARE @str Nvarchar(50) -- 中间字符串,用于存储***次转换之后的日期字符
- DECLARE @Year Int,@Month Int,@Day Int -- 获取函数传入的时间参数的年月日的值
- DECLARE @strYear Nvarchar(50),@strMonth Nvarchar(50),@strDay Nvarchar(50) -- 中间字符串,分别用于存储***次转换之后的年月日字符串
- declare @e Nvarchar(10),@n Nvarchar(10),@index Int,@result Nvarchar(50) -- @e,@n和@index用于字符串比对,将@e中@index位置出现的字符替换成@n中@index位置的字符,@result用于存储最终处理完成的日期字符串,并作为返回结果
- SELECT @e='0123456789',@n='〇一二三四五六七八九',@index=1
- SET @Year = Year(@dt)
- SET @Month = Month(@dt)
- SET @Day = Day(@dt)
- -- 生成年
- SET @strYear = Cast(@Year AS Nvarchar(50)) + '年'
- -- 生成月
- IF(@Month < 10)
- SET @strMonth = Cast(@Month AS Nvarchar(50))
- ELSE IF(@Month = 10)
- SET @strMonth = '十'
- ELSE IF(@Month > 10)
- SET @strMonth = '十' + Cast((@Month - 10) AS Nvarchar(50))
- SET @strMonth = @strMonth + '月'
- -- 生成日
- IF(@Day < 10)
- SET @strDay = Cast(@Day AS Nvarchar(50))
- ELSE IF(@Day = 10)
- SET @strDay = '十'
- ELSE IF(@Day > 10 AND @Day < 20)
- SET @strDay = '十' + Cast((@Day - 10) AS Nvarchar(50))
- ELSE IF(@Day = 20)
- SET @strDay = '二十'
- ELSE IF(@Day > 20 AND @Day < 30)
- SET @strDay = '二十' + Cast((@Day - 20) AS Nvarchar(50))
- ELSE IF(@Day = 30)
- SET @strDay = '三十'
- ELSE IF(@Day = 31)
- SET @strDay = '三十一'
- SET @strDay = @strDay + '日'
- -- 拼接年月日
- SET @str = @strYear + @strMonth + @strDay
- WHILE @index<=Len(@str)
- BEGIN
- DECLARE @s Nvarchar(1)
- SET @s=SubString(@str,@index,1)
- IF CharIndex(@s,@e)>0
- SET @result=IsNull(@result,'')+SubString(@n,CharIndex(@s,@e),1)
- ELSE
- SET @result=IsNull(@result,'')+@s
- SET @index=@index+1
- END
- RETURN @result
- END
- GO
【本文是51CTO专栏作者张勇波的原创文章,转载请通过51CTO获取作者授权】