Hi All there,
I just came across an issue that's related to extracting the data of previous month and manupulating it to generate a report. I think this is a general issue. So far I have been contacted by two of my friends/ex-colleagues, to get it solved this. So I thought, if there could be a definitive solution for this, it would help others too who have similar issues. Since we are into the new year, and this was not coded keeping the year change in mind, and they have told me that it suddenly does not return the previous month's data. When I looked in to it, I came to know the year change issue was not kept in mind and designed. So I have given this as a solution.
Not only that I thought I would share this with you all here, so as to get better opinion or solution for the same as this forum has got a lot many sql gurus. May be others have different and easy approach for the same. I am eagar to know that.
Please take a look at it in your leisure time and post your opinions if any.
The following code returns the start and end date/time of the Previous month, based on which the data can be extracted later, which is not included in this.
Eg: -
@startdate = '2003-12-01 00:00:00.000'
@enddate = '2003-12-31 23:59:59.999'
__________________________________________________ ___
Code:
declare @startdate varchar(25), @enddate varchar(25)
If (datepart(m,getdate()) = 1)
Begin
select @startdate=convert(varchar(4),datepart(yyyy,dateadd(yyyy,-1,getdate()))) + '-' + convert(varchar(2),datepart(mm,dateadd(mm,-1,getdate()))) + '-01 00:00:00.000'
select @enddate=convert(varchar(4),datepart(yyyy,dateadd(yyyy,-1,getdate()))) + '-' + convert(varchar(2),datepart(mm,dateadd(mm,-1,getdate()))) + '-' + convert(varchar(2),datepart(dd,dateadd(dd,-datepart(dd,getdate()),getdate()))) + ' 23:59:59.999'
End
Else
Begin
select @startdate=convert(varchar(4),datepart(yyyy,getdate())) + '-' + convert(varchar(2),datepart(mm,dateadd(mm,-1,getdate()))) + '-01 00:00:00.000'
select @enddate=convert(varchar(4),datepart(yyyy,getdate())) + '-' + convert(varchar(2),datepart(mm,dateadd(mm,-1,getdate()))) + '-' + convert(varchar(2),datepart(dd,dateadd(dd,-datepart(dd,getdate()),getdate()))) + ' 23:59:59.999'
End
select @startdate, @enddate
Thanks in advance for your time and effort on this.
-Vijay G