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 2008 Forums
 Transact-SQL (2008)
 How to format YYYYMM

Author  Topic 

duanecwilson
Constraint Violating Yak Guru

273 Posts

Posted - 2010-07-06 : 15:56:52
I just need to put into a string for a flat file output the year and month for last month with the following format: YYYYMM. I thought this would be the most simple thing on my list. But I can't find it anywhere. I definitely need the 0 for the single months as we need 6 digits in the column.

Duane

robvolk
Most Valuable Yak

15732 Posts

Posted - 2010-07-06 : 16:07:20
SELECT CONVERT(char(6), DateAdd(month, DateDiff(month, 0, getdate())-1, 0), 112)
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2010-07-06 : 16:36:08
[code]select YYYYMM = convert(char(6),dateadd(mm,-1,getdate()),112)[/code]Results:
[code]YYYYMM
------
201006

(1 row(s) affected)[/code]

CODO ERGO SUM
Go to Top of Page

duanecwilson
Constraint Violating Yak Guru

273 Posts

Posted - 2010-07-06 : 16:55:17
Thank you for both of these. They both work.

Duane
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-07-07 : 03:42:49
Another method

select convert(char(6),getdate()-day(getdate()),112)


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

duanecwilson
Constraint Violating Yak Guru

273 Posts

Posted - 2010-07-07 : 10:47:24
Thank you madhivanan. This one works as well. Now I'll have several from which to choose. I don't know which one is most efficient, but it doesn't matter as they all are under 1 second.

Duane
Go to Top of Page
   

- Advertisement -