Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 how to find first and last day of the month

Author  Topic 

ms.gangadhar
Starting Member

8 Posts

Posted - 2012-06-05 : 03:05:17
Hi,

I order to run a report for a particular month i need to fidn the first and last day of the month.How can we do this.

Regards,
Gangadhara

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2012-06-05 : 03:13:14
-- -----------------------------------------
-- get 1. day of actual month
-- -----------------------------------------
Select DateAdd(Month,DateDiff(Month,0,getdate()),0)

-- ----------------------------------------------
-- get LAST day of actual month
-- ----------------------------------------------
Select DateAdd(dd,-1,DateAdd(Month,DateDiff(Month,0,getdate())+1,0))


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2012-06-05 : 05:23:05
You may also need to look at the code shown at the bottom of this post
http://beyondrelational.com/modules/2/blogs/70/posts/10899/understanding-datetime-column-part-iii.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

jeffw8713
Aged Yak Warrior

819 Posts

Posted - 2012-06-05 : 14:13:04
quote:
Originally posted by webfred

-- -----------------------------------------
-- get 1. day of actual month
-- -----------------------------------------
Select DateAdd(Month,DateDiff(Month,0,getdate()),0)

-- ----------------------------------------------
-- get LAST day of actual month
-- ----------------------------------------------
Select DateAdd(dd,-1,DateAdd(Month,DateDiff(Month,0,getdate())+1,0))


No, you're never too old to Yak'n'Roll if you're too young to die.



For last day of the month, it is simpler to use:

DATEADD(month, DATEDIFF(month, -1, getdate()), -1)

Or, to move forward/backward xx number of months:

DATEADD(month, DATEDIFF(month, -1, getdate()) + xx, -1); -- where xx is the number of months forward/backward
Go to Top of Page
   

- Advertisement -