当我执行下面的查询
DECLARE @I INT=1 while(@I<13) BEGIN PRINT DATENAME(MONTH,@I) PRINT @I SET @I=@I+1 END
我有输出像:
January 1 January 2 January 3 January 4 January 5 January 6 January 7 January 8 January 9 January 10 January 11 January 12
为什么所有月份名称都不打印在上述结果中?任何人都可以指明原因吗?
因为当您使用DATENAME(MONTH,@I)
值1,2,3,4 ...被隐式转换为DATETIME
:
SELECT CAST(1 AS DATETIME) -- 1900-01-02 00:00:00 1 - Jan 2 1900 12:00AM 2 - Jan 3 1900 12:00AM 3 - Jan 4 1900 12:00AM ... 12 - Jan 13 1900 12:00AM
并且DATENAME
对于月份来说总是如此January
你可以DATEADD
用来获得所有月份:
DECLARE @I INT=1 while(@I<13) BEGIN PRINT DATENAME(MONTH, DATEADD(MONTH, @i-1, '2000-01-01')) PRINT @I SET @I=@I+1 END
LiveDemo