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
 Year To Date Syntax in SQL Server 2008

Author  Topic 

Lizzie_gurl
Starting Member

11 Posts

Posted - 2011-09-21 : 14:31:02
Hi Guys,

Need help, how do i write Year To Date in SQL Server 2008 if i want to get the current Year to Date data?

And for Month To date as well.

Please help!

Thanks!





Lizzie :-)

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-09-21 : 15:08:56
Maybe this will help:
SELECT
CAST(CURRENT_TIMESTAMP AS DATE) AS CurrentDate,
DATEADD(YEAR, DATEDIFF(YEAR, 0, CURRENT_TIMESTAMP), 0) StartOfCurrentYear,
DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0) StartOfCurrentMonth
Go to Top of Page

flamblaster
Constraint Violating Yak Guru

384 Posts

Posted - 2011-09-21 : 16:49:50
Lizzie, similar to what Lamprey posted, if you're needing to get everything between the beginning of the year and say the end of "last month" which is usually the case for me, you could do something like this:

[CODE]
declare @StartOfCurrentYear date
declare @EndOfLastMonth date

declare @sample table (ServiceDate date, SomeData varchar(10))
insert into @sample (ServiceDate, SomeData)
values ('20110131', 'testing'), ('20110813', 'Comments')

select @StartOfCurrentYear= DATEADD(YY, DATEDIFF(YY, 0, GETDATE()),0)
select @EndOfLastMonth= DATEADD(MM, DATEDIFF(MM, 0, GETDATE()),0)-1

select *
from @sample
where ServiceDate between @StartOfCurrentYear and @EndOfLastMonth


(2 row(s) affected)
ServiceDate SomeData
----------- ----------
2011-01-31 testing
2011-08-13 Comments

(2 row(s) affected)

[/CODE]

EDIT: Added results
Go to Top of Page

Lizzie_gurl
Starting Member

11 Posts

Posted - 2011-09-21 : 17:14:04
thank you guys so much, i will try these syntax :-)

Lizzie :-)
Go to Top of Page
   

- Advertisement -