HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMajor

Convert date yyyy-mm-dd to integer YYYYMM

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
yyyymmconvertyyyydateinteger

Problem

How can I convert @dateb:

SET @dateb = dateadd(month, datediff(month, 0, getdate()) - 3, 0)


that returns 2014-04-04 as date to an integer of 201404

Thanks

Solution

On version 2012 or higher you can use the format function to get just year and month, then cast it as an int.

On versions prior to 2012 you can do the formatting with the convert function, then cast as int.

declare @dateb datetime
set @dateb = getdate()

select cast(format(@dateb,'yyyyMM') as int) --2012 or higher
select cast(convert(varchar(6),@dateb,112) as int) -- all versions

Code Snippets

declare @dateb datetime
set @dateb = getdate()

select cast(format(@dateb,'yyyyMM') as int) --2012 or higher
select cast(convert(varchar(6),@dateb,112) as int) -- all versions

Context

StackExchange Database Administrators Q#106898, answer score: 22

Revisions (0)

No revisions yet.