May 25, 2010 at 12:11 pm
I need to run a query based off of a rolling year's data, which for the startdate I found online as so:
SELECT DATEADD(year, -1, dateadd(s,-1,dateadd(dd,datediff(dd,0,getdate()),0)))
It's great, gives me today's date but for last year. Unfortunately, I need it in calendar format. I tried just adding the CONVERT with 101 format, but of course that didn't work so well. I'm not so on-top of the date functions and converting and formatting, etc, so I'm a little lost on this....
Help?
May 25, 2010 at 12:20 pm
Please define "calendar format".
If you're using the date in a query, you'll want it to remain a DATETIME field unless the dates in your table are in some weird format.
--J
May 25, 2010 at 12:25 pm
It needs to be in calendar format for the query:
05/25/2010
If I could also have it in ldate format, (20100525) that would be great too.....but either would work for me.
May 25, 2010 at 12:28 pm
CONVERT 101 should work fine then.
SELECT CONVERT(VARCHAR,DATEADD(year, -1, dateadd(s,-1,dateadd(dd,datediff(dd,0,getdate()),0))),101)
Returns "05/24/2009". But, it returns it as a VARCHAR, not a datetime. You should not use a VARCHAR for date comparisons. If the dates in your table are stored as VARCHARs (I hope for your sake they aren't), then you should convert the table VARCHAR dates to DATETIMEs, instead of the other way around.
--J
May 25, 2010 at 12:31 pm
select CONVERT(varchar(11),getdate(),101) -- produces 05/25/2010
select CONVERT(varchar(11),getdate(),108) -- produces 20100525
May 25, 2010 at 12:34 pm
select CONVERT(varchar(11),DATEADD(YY,-1,getdate()),101) -- would give you last year.
May 25, 2010 at 12:38 pm
Thank you everyone for the quick and knowledgeable responses! This works wonderfully now.
Thank you so much!
May 25, 2010 at 3:54 pm
tacy.highland (5/25/2010)
Thank you everyone for the quick and knowledgeable responses! This works wonderfully now.Thank you so much!
Tray... I have a concern about your floating year code with the date format you've chosen. Any chance of you posting your code and the CREATE TABLE statement?
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply