1

可能重复:
两个日期之间的月份

我需要带来结果,两个日期之间的月份是多少。

例如。假设日期是

Declare @FrDate datetime,@ToDate datetime
Set @FrDate ='2010-05-31 17:38:58.577' 
Set @ToDate ='2010-09-01 17:38:58.577'

需要输出

Result
MAY
JUN
JUL
AUG
SEP
4

3 回答 3

2

试试这个:

DECLARE @FrDate  DATETIME,
        @ToDate    DATETIME;

Set @FrDate ='2010-05-31 17:38:58.577' 
Set @ToDate ='2010-09-01 17:38:58.577'

;WITH MONTHS (date)
AS
(
    SELECT @FrDate
    UNION ALL
    SELECT DATEADD(month,1,date)
    from months
    where date<=@ToDate
)
SELECT Datename(month,date) AS MONTH FROM MONTHS

结果:

MONTH
-----------------
May
June
July
August
September

(5 row(s) affected)

要在结果中获得短月份名称,您可以使用以下行:

SELECT LEFT(CONVERT(VARCHAR,date,100),3) AS MONTH FROM MONTHS

要获取大写的月份名称,您可以使用UPPER以下函数:

SELECT UPPER(LEFT(CONVERT(VARCHAR,date,100),3)) AS MONTH FROM MONTHS
于 2012-10-03T12:46:19.257 回答
0

创建一个日历表,然后你可以简单地这样写:

select distinct MonthName
from dbo.Calendar
where BaseDate between @StartDate and @EndDate
于 2012-10-03T13:00:16.840 回答
0

另一种方法

Declare @FrDate datetime,@ToDate datetime 
Set @FrDate ='2010-05-31 17:38:58.577'  
Set @ToDate ='2010-09-01 17:38:58.577' 

select 
    datename(month,dateadd(month,number-1,@FrDate)) as month_name
from 
    master..spt_values 
where 
    type='p'and number between 1 and datediff(month,@frdate,@todate)+1
于 2012-10-03T13:12:59.420 回答