DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE
SITE SEARCH SQLUSA.com HEADLINES NEWS
SQL E/BOOKS   SQL 2014 PROGRAMMING   DOWNLOADS
SCRIPTS SQL 2005 SQL 2008 ARTICLES
SQL JOBS TWITTER FORMAT VIDEOS
How to calculate days in a month?

The following Microsoft SQL Server T-SQL scripts demonstrate how to compute days in a month:

------------

-- Days in a month for date range - sequence generation

------------

DECLARE @StartDate DATE = '20000101',@EndDate DATE ='20160601';

WITH CTE AS(

      SELECT      1 MonthNo, CONVERT(DATE, @StartDate) MonthFirst,

                  DATEDIFF(DD,@StartDate,DATEADD(MM,1,@StartDate)) AS Days

      UNION ALL

      SELECT      MonthNo+1, DATEADD(Month, 1, MonthFirst),

                  DATEDIFF(DD,DATEADD(Month, 1, MonthFirst),DATEADD(MM,1,DATEADD(Month, 1, MonthFirst)))

      FROM  CTE

      WHERE MonthFirst < @EndDate)

SELECT  YEAR(MonthFirst) AS [Year],

        DATENAME(MONTH, MonthFirst) AS MonthName,

        Days

FROM  CTE

ORDER BY MonthNo

OPTION (MAXRECURSION 0);

------------

 

Year

MonthName

Days

2000

January

31

2000

February

29

2000

March

31

2000

April

30

2000

May

31

 

Related articles:

 

http://sqlusa.com/bestpractices2005/sequence/

 

http://www.sqlusa.com/bestpractices/datetimeconversion/

 

Exam Prep 70-461
Exam 70-461
DATETIME SELECT SELECT INTO DATE PAD STRING DYNAMIC SQL CURSOR MONEY FORMAT PERCENT STORED PROCEDURE SQL SERVER AGENT JOB OPTIMIZATION WHILE LOOP OVER PARTITION BY UPDATE