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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Get Year + Month from Datetime

Author  Topic 

Will H
Yak Posting Veteran

56 Posts

Posted - 2007-11-30 : 12:01:46
Hi - Anyone have suggestions for converting a datetime to just the year and month, while setting day to 1 and time to zero (12am)??

I've been using something like this:

SELECT Convert(DateTime, Convert(varchar(4), YEAR(GetDate())) + '-' + Convert(Varchar(2), MONTH(GetDate())) + '-01')

-- Input: 2007-11-30 08:58:56.463
-- Output: 2007-11-01 00:00.000

This is the exact input/output I would like, but the problem is it ends up being a lot to type over and over. I don't have permissions to write a UDF on the database. I'm wondering if anyone has any ideas on getting this same functionality w/ less typing or better effeciency.

Thnx - will

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2007-11-30 : 12:42:02
[code]Select dateadd(mm,datediff(mm,0,MyDateTime),0)[/code]

Start of Time Period Functions:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=64755
Start of Week Function:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47307

Finding the End of Time Periods
End Date of Time Period Functions:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=64759
End of Week Function:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=64760



CODO ERGO SUM
Go to Top of Page

Will H
Yak Posting Veteran

56 Posts

Posted - 2007-11-30 : 13:22:51
Beautiful, thanks man!

---------------------------------------------------------
SSRS Kills Kittens.
Go to Top of Page

jsmith8858
Dr. Cross Join

7423 Posts

Posted - 2007-11-30 : 14:08:32
more here on grouping by month: http://weblogs.sqlteam.com/jeffs/archive/2007/09/10/group-by-month-sql.aspx

- Jeff
http://weblogs.sqlteam.com/JeffS
Go to Top of Page
   

- Advertisement -