Thursday, 11 August 2016

How to display 12 months name in sql server

DECLARE @YEAR INT
SET @YEAR = (SELECT YEAR(GETDATE()))
DECLARE @MONTH INT
SET @MONTH = (SELECT MONTH(GETDATE()))

DECLARE @DT TABLE(ID INT, MONTHNAME NVARCHAR(20))

INSERT INTO @DT SELECT NUMBER AS ID,
   DATENAME(MONTH, CAST(@YEAR*100+NUMBER AS VARCHAR) + '01')  AS MONTHNAME
FROM MASTER.DBO.SPT_VALUES  
WHERE TYPE = 'P' AND 
  NUMBER BETWEEN @MONTH AND 12

INSERT INTO @DT SELECT NUMBER AS ID,
   DATENAME(MONTH, CAST(@YEAR*100+NUMBER AS VARCHAR) + '01')  AS MONTHNAME

FROM MASTER.DBO.SPT_VALUES  
WHERE TYPE = 'P' AND 
  NUMBER BETWEEN 1 AND @MONTH -1

SELECT * FROM @DT

No comments:

Post a Comment