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
 Getting the month to date

Author  Topic 

Petronas
Posting Yak Master

134 Posts

Posted - 2012-02-23 : 11:20:50
Hi,

I have to calculate YTD numbers and also have the numbers broken down by each month to date.
I have the following:

DECLARE
@now DATETIME = GETDATE(),
@start_date DATETIME,
@end_date DATETIME,

SELECT @start_date = convert(varchar,DATEADD(yy, DATEDIFF(yy,0,@now), 0),111)---YTD
SELECT @end_date = CONVERT(VARCHAR, @now, 101)

I am using the @start_date and @end_date in the query to get the numbers for YTD part.
How can I get a month_start_date and month_end_date so that I can use it in my query which calculates the total numbers broken down by January and Feb and for next month they will be broken down by January, Feb and March and so forth.
I am using SQl Server 2008.

Thanks in advance
Petronas.

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2012-02-23 : 12:11:07
[code]DECLARE
@now DATETIME = GETDATE(),
@start_date DATETIME,
@end_date DATETIME

SET @start_date = DATEADD(YEAR, DATEDIFF(YEAR, 0, @now), 0)
SET @end_date = DATEADD(MONTH, DATEDIFF(MONTH, 0, @now) + 1, 0)


SELECT <col_list>
FROM <table_name>
WHERE <date_col> >= @start_date
AND <date_col> < @end_date[/code]
Go to Top of Page
   

- Advertisement -