Search This Blog

Monday, July 1, 2013

Find Number of Days in a Given Month

How many lines of code do you need to write to get number of days in a given month , there is no handy function available in SQL Server which does the job.

Say 12 If statements or combine Month which has 30 and 31 with just IF Statements .. And how about February which may have 28 or 29 depending on leap year or not.

Below mentioned code returns data with single statement when a date is provided as input.

SET NOCOUNT ON

DECLARE @dt DATETIME
SELECT  @dt = '2012-07-01'
SELECT DAY(DATEADD(MONTH,1,DATEADD(DAY,1-DAY(@dt),@dt))-1) AS DaysInGivenMonth


/*
--Section below explains logic step of step how this is calculated...

SELECT DAY(@dt) 'Day from the date specified'
SELECT 1-DAY(@dt) 'One day before the date'
SELECT DATEADD(DAY,1-DAY(@dt),@dt) 'Find the start of month'
SELECT DATEADD(MONTH,1,DATEADD(DAY,1-DAY(@dt),@dt)) 'Find prev month'
SELECT DATEADD(MONTH,1,DATEADD(DAY,1-DAY(@dt),@dt))-1 'Subtract one day'

SET NOCOUNT OFF
*/

In SQL 2012

DECLARE @dt DATETIME
SELECT  @dt = '2012-07-01'
SELECT DATEPAT(dd,EOMONTH (@dt))

No comments: