Convert month number to month name in SQL Server
In SQL Server, month numbers are usually stored as integers (e.g., 1 for January, 2 for February, etc.). To display these numbers as corresponding month names (for example, 1 for January, 2 for February), a common solution is to use a CASE expression. However, for an easier approach, consider the following function:
Use the DateName() function
DateName() function can be used to extract a specific part of a date value. To get the month name from the month number, use the following syntax:
DateName(month , DateAdd( month , @MonthNumber , 0 ) - 1 )
or
DateName(month , DateAdd( month , @MonthNumber , -1 ) )
The first expression subtracts a day from the month to align with the month name, while the second expression subtracts a month.
Example
Consider a table with a column called "MonthNumber" containing month numbers. To display month names, use the following query:
SELECT MonthNumber, DateName(month, DateAdd(month, MonthNumber, 0) - 1) AS MonthName FROM TableName;
This query will return the month number and its corresponding month name.
The above is the detailed content of How to Convert Month Numbers to Month Names in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!