ISO long (112) 可以解决问题:
SELECT CONVERT(INT, CONVERT(VARCHAR(8), GETDATE(), 112))
出于某种原因,使用 ISO 112 将 getdate() 直接转换为 int 会得到 41008,但通过 VARCHAR 似乎可行 - 如果我想到更快的转换,我会更新。
编辑:关于仅 int 与 varchar 的辩论,这是我的发现(可在我的测试台和生产服务器上重复) Varchar 方法使用更少的 cpu 时间来进行 50 万次投射,但总体速度要慢一点 - 可以忽略不计,除非你处理数十亿行
编辑 2:修改测试用例以清除缓存和不同的日期
DBCC FREEPROCCACHE;
DBCC DROPCLEANBUFFERS;
SET STATISTICS TIME ON;
WITH RawDates ( [Date] )
AS ( SELECT TOP 500000
DATEADD(DAY, N, GETDATE())
FROM TALLY
)
SELECT YEAR([Date]) * 10000 + MONTH([Date]) * 100 + DAY([Date])
FROM RawDates
SET STATISTICS TIME OFF
(500000 row(s) affected)
SQL Server Execution Times:
CPU time = 218 ms, elapsed time = 255ms.
DBCC FREEPROCCACHE;
DBCC DROPCLEANBUFFERS;
SET STATISTICS TIME ON;
WITH RawDates ( [Date] )
AS ( SELECT TOP 500000
DATEADD(DAY, N, GETDATE())
FROM TALLY
)
SELECT CONVERT(INT, CONVERT(VARCHAR(8), [Date], 112))
FROM RawDates
SET STATISTICS TIME OFF
(500000 row(s) affected)
SQL Server Execution Times:
CPU time = 266 ms, elapsed time = 602ms