简体   繁体   中英

How to get Next Month in Mon yyyy Format?

I have one table that get dates as SaleDate formatted like this

##SaleDate##
_________
Oct 13  
--------
Nov 13  
--------  
Dec 13  
-------- 
Jan 14  
--------  

How can I get the next month from previous date formats?

By setting min and max date you can get the list of date like below

       DECLARE @OldestDate DATE
    DECLARE @maxDate DATE 
    SET @OldestDate = '09/29/2013' -- (SELECT MIN(SALEDATE) FROM YOURTABLE)
    SET @maxDate = '12/19/2014' -- (SELECT MAX(SALEDATE) FROM YOURTABLE)

 ; WITH dates([DateCounter]) AS 
  (
    SELECT @OldestDate AS [DateCounter] 
    UNION ALL 
    SELECT DATEADD(month,+1,[DateCounter])
    FROM DATES 
    WHERE [DateCounter] < CAST(@maxDate AS DATE)
  )

    SELECT LEFT(DATENAME(MONTH,[DateCounter]),3) + ' ' + DATENAME(YEAR,[DateCounter])
    FROM dates
    OPTION (MAXRECURSION 0) 

Here is the working example on SQLFiddler

With some long convoluted inline functions:

DECLARE @V VARCHAR(6)
SET @V = 'Jan 14'

SELECT RIGHT(CONVERT(VARCHAR(9),DATEADD(m,1,CONVERT(DATETIME,'01 ' + @V,106)),6),6)


SELECT RIGHT(
    CONVERT(
        VARCHAR(9),
            DATEADD(m,1,CONVERT(DATETIME,'01 ' + SaleDate,106))
        ,6)
 ,6)
FROM YourTable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM