SQL用于显示两个日期之间的月份和年份

时间:2013-10-16 19:55:31

标签: sql sql-server tsql

我有四个变量CurrentMonth,CurrentYear,Month,year。我想要一个SQL语句,显示(Month,Year)到(currentMonth,CurrentYear)之间的所有月份和年份。下面显示几个月,但我需要几个月和一年,我没有日期,但只有开始和结束的月份和年份。

DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME;

SELECT   @StartDate = '20110501'        
        ,@EndDate   = '20110801';


SELECT  DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS MonthName
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'        
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate);

1 个答案:

答案 0 :(得分:3)

这是对前一个答案的修改,以满足您的月/年需求。

    DECLARE @FromMonth varchar(2), @FromYear varchar(4), @ToMonth as Varchar(2), @ToYear as varchar(4)
    SET @FromMonth = '01';
    SET @FromYear = '1944';
    SET @ToMonth = '04';
    SET @ToYear = '1956';


    DECLARE @DateFrom smalldatetime, @DateTo smalldatetime;
    SET @DateFrom=@FromYear+@FromMonth+'01';
    SET @DateTo=@ToYear+@ToMonth+'01';
    -------------------------------
    WITH T(date)
    AS
    ( 
    SELECT @DateFrom 
    UNION ALL
    SELECT DateAdd(month,1,T.date) FROM T WHERE T.date < @DateTo
    )

    SELECT  datename(m,date) + '-' + datename(yy,date) as DN FROM T 
     OPTION (MAXRECURSION 32767);