May 24, 2012 at 12:44 pm
Can Anyone explain the logic to behind to get the first day of the month
SELECT dateadd(MM,datediff(MM,0,getdate()),0)
May 24, 2012 at 12:59 pm
Jay Pete (5/24/2012)
Can Anyone explain the logic to behind to get the first day of the monthSELECT dateadd(MM,datediff(MM,0,getdate()),0)
To understand this you first have to break it apart.
The second parameter inside the outer dateadd is
datediff(MM,0,getdate())
This gets the number of months since the "0" date or 1/1/1900. As of today's posting that is 1,348.
Then you simply use the dateadd function to add that many months to 1/1/1900. So if you add 1,348 months to 1/1/1900 you will get 5/1/2012.
Make sense now?
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
May 24, 2012 at 1:30 pm
Sean Lange (5/24/2012)
This gets the number of months since the "0" date or 1/1/1900. As of today's posting that is 1,348.
Just to emphasise, the reason it works is that this part of the query returns a whole number of months.
May 24, 2012 at 1:58 pm
I suspect Paul will link to this article. One I keep close at hand myself.
http://www.sqlteam.com/article/datediff-function-demystified
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply