将日期 yyyy-mm-dd 转换为整数 YYYYMM

Mar*_*sen 18 sql-server

我如何转换@dateb:

SET @dateb = dateadd(month, datediff(month, 0, getdate()) - 3, 0)
Run Code Online (Sandbox Code Playgroud)

2014-04-04作为日期返回到整数201404

谢谢

Bob*_*mes 21

在 2012 或更高版本上,您可以使用该format函数获取年和月,然后将其转换为 int。

在 2012 之前的版本上,您可以使用该convert函数进行格式化,然后转换为 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
Run Code Online (Sandbox Code Playgroud)

  • [我通常会避免`FORMAT()`](http://sqlperformance.com/2015/06/t-sql-queries/format-is-nice-and-all-but)。天啊。 (6认同)

Aar*_*and 17

也许更整洁一点:

SELECT YEAR(@dateb)*100 + MONTH(@dateb);
Run Code Online (Sandbox Code Playgroud)

  • 我完全同意这一点。您有一个日期,其中包含整数子字段;你想要一个整数。到底为什么要进行字符串处理? (2认同)