Ecco tre funzioni T-SQL che puoi utilizzare per estrarre il mese da una data in SQL Server.
MONTH()
La funzione più ovvia da usare è MONTH() funzione. Questa funzione accetta un argomento:la data.
DECLARE @date date = '2020-10-25';
SELECT MONTH(@date); Risultato:
10
DATEPART()
Il DATEPART() La funzione accetta due argomenti:il primo argomento è la parte della data che vuoi estrarre e il secondo argomento è la data effettiva da cui vuoi estrarlo.
DECLARE @date date = '2020-10-25';
SELECT DATEPART(month, @date); Risultato:
10
In questo esempio ho usato month come primo argomento. Hai anche la possibilità di usare mm o m . Qualunque cosa tu usi, il risultato è lo stesso.
DECLARE @date date = '2020-10-25'
SELECT
DATEPART(month, @date) AS month,
DATEPART(mm, @date) AS mm,
DATEPART(m, @date) AS m; Risultato:
+---------+------+-----+ | month | mm | m | |---------+------+-----| | 10 | 10 | 10 | +---------+------+-----+
FORMAT()
Il FORMAT() la funzione può essere utilizzata anche per restituire il mese.
DECLARE @date date = '2020-10-25';
SELECT FORMAT(@date, 'MM'); Risultato:
10
In alternativa puoi usare MMMM per restituire il nome completo del mese o MMM per restituire il nome breve del mese.