可能重复:
两个日期之间的月份
我需要带来结果,两个日期之间的月份是多少。
例如。假设日期是
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
可能重复:
两个日期之间的月份
我需要带来结果,两个日期之间的月份是多少。
例如。假设日期是
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
试试这个:
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
创建一个日历表,然后你可以简单地这样写:
select distinct MonthName
from dbo.Calendar
where BaseDate between @StartDate and @EndDate
另一种方法
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