昨天在SQL Server中转换为YYYYMMDD格式

问题描述 投票:0回答:2

我正在为已经表现不佳的SQL代码添加条件。我想添加一个过滤器,其中日期=昨天(数据类型为INT)。

例如

Select * 
From table
Where Date = 20190930

如何使用GETDATE() - 1执行此操作?

sql sql-server date-formatting
2个回答
0
投票

这是您的查询。首先,您是否需要在转换为datetime之前将int date转换为vachar,以避免在转换期间进行算术运算。

第二,您需要强制转换getdate-1作为日期以截断时间以匹配日期字段。

select *
from table
where cast((cast(date as varchar(8))as datetime) = cast(getdate() - 1 as date)

select *
from table
where cast((cast(date as varchar(8)) as date) = cast(dateadd(day,datediff(day,1,GETDATE()),0) as date)

1
投票

我们需要非常清楚所使用的数据类型。

如果您有一个简单的date值(数据类型中没有时间成分,那么事情很简单:

Select * 
from table
where Date = DATEADD(day, -1, cast(current_timestamp as date))

如果您具有DateTimeDateTime2值,则重要的是要了解所有DateTime值的时间分量一直下降到毫秒。即使您希望时间部分总是在午夜或午夜附近,也是如此。这可能会使直接相等比较变得困难。相反,您几乎总是需要在特定的[[range:

中进行检查Select * from table where Date >= DATEADD(day, -1, cast(current_timestamp as date)) AND Date < cast(current_timestamp as date)
© www.soinside.com 2019 - 2024. All rights reserved.