SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Date add
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Joshrinn
Posting Yak Master

118 Posts

Posted - 06/25/2012 :  09:16:02  Show Profile  Reply with Quote
I was wondering how do I get this right. I did dateadd(mm,1, '04-30-2012') and it gives me '05-30-2012) but in reality in want it to auto recognize the months which has 30 days and 31 days. It should have been '05-31-2012'. How do I get this.
Thanks in advance

sunitabeck
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 06/25/2012 :  10:08:22  Show Profile  Reply with Quote
quote:
Originally posted by Joshrinn

I was wondering how do I get this right. I did dateadd(mm,1, '04-30-2012') and it gives me '05-30-2012) but in reality in want it to auto recognize the months which has 30 days and 31 days. It should have been '05-31-2012'. How do I get this.
Thanks in advance

You can use one or the other of the below selects. Both are really doing the same thing:
DECLARE @date DATETIME = '20120430';
SELECT DATEADD(mm,DATEDIFF(mm,0,@date)+2,-1);
SELECT DATEADD(mm,DATEDIFF(mm,'19000101',@date)+2,'18991231');
Go to Top of Page

jeffw8713
Aged Yak Warrior

USA
696 Posts

Posted - 06/25/2012 :  15:27:27  Show Profile  Reply with Quote
To get the end of the current month: dateadd(month, datediff(month, -1, getdate()), -1)
To get the end of the previous month: dateadd(month, datediff(month, -1, getdate()) - 1, -1)

To filter in a where clause for the previous month:

WHERE datecolumn >= dateadd(month, datediff(month, 0, getdate()) - 1, 0) -- first of previous month
AND datecolumn < dateadd(month, datediff(month, 0, getdate()), 0) -- first of current month

In other words, don't filter on the last day of the month - filter on anything *less* than the first day of the next month.

Jeff
Go to Top of Page

madhivanan
Premature Yak Congratulator

India
22461 Posts

Posted - 06/26/2012 :  03:09:10  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
You can find some effecient date-querying at 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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000