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
 General SQL Server Forums
 New to SQL Server Programming
 returning last date of previous month

Author  Topic 

dmills99
Starting Member

7 Posts

Posted - 2011-01-06 : 09:47:01
right now i have code:

RETURN DateAdd(second, -1, dbo.DateSerial((YEAR(@indate) + case when MONTH(@indate) IN (1,2) then 0 else -1 end), 3, 1))

if you run this on 1/6/2011 it returns 2/28/2011 which is a date in the future, but the end of a fiscal year for one of our reports...

how can i change this so that if I run it on 1/6/2011 it always goes back and finds the end of the previous month : ie: 12/31/2010

thanks in advance for any response

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2011-01-06 : 10:05:50
select dateadd(dd,-1*datepart(dd,getdate()),dateadd(dd,datediff(dd,0,GETDATE()),0))

or
convert(datetime,convert(varchar(6),getdate(),112)+'01')-1

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2011-01-06 : 10:10:01
select dateadd(month,datediff(month,0,'20110106'),-1)

Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-01-12 : 04:37:40
If time doesn't matter

select getdate()-day(getdate())

Madhivanan

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

dmills99
Starting Member

7 Posts

Posted - 2011-01-19 : 15:56:59
thanks for all your help...
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2011-01-19 : 16:47:06
Keep it simple
SELECT	DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), -1)



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -