Home > Database > Mysql Tutorial > How to Convert Month Numbers to Month Names in SQL Server?

How to Convert Month Numbers to Month Names in SQL Server?

Barbara Streisand
Release: 2025-01-18 19:16:08
Original
310 people have browsed it

How to Convert Month Numbers to Month Names in SQL Server?

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 )
Copy after login

or

DateName(month , DateAdd( month , @MonthNumber , -1 ) )
Copy after login

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;
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template