昨天在Microsoft SQL Server Management Studio中的动态语句

问题描述:

我运行下面的查询来检查前一天是否运行。下面的查询工作,但我必须每天更改日期以获得我想要的结果。我已经尝试了多种东西,我发现它们看起来像他们应该返回结果,但他们似乎不工作。昨天在Microsoft SQL Server Management Studio中的动态语句

select * from Linking_Results 
where Evaluated between '2015-02-04 00:00:01.001' and '2015-02-04 23:59:00.999' 
and Linked = '1' order by Evaluated 

所以我的问题是,我如何做一个昨天的动态声明,并保持不必每天更改日期?

+0

MySQL或SQL Server 2008?他们是非常不同的产品。 @paul你确定要从标题中删除SQL Server 2008吗? – Taryn 2015-02-05 16:20:23

+0

@bluefeet因为标签和upvoted的答案,我去了MySQL。原标题是'My SQL Server 2008',令人困惑。 – paul 2015-02-05 16:25:52

+0

@paul不幸的是,标签和标题通常都是错误的。很多人都提到'mysql服务器',并指**我的**'sql服务器'。 – Taryn 2015-02-05 16:27:08

您可以使用dateaddgetdate函数。

declare @start datetime, 
     @end datetime 

-- subtract one day and cast it as a date to drop the time portion 
select @start = cast(dateadd(day, -1, getdate()) as date) 
-- add one day and subtract 3ms to get the end of yesterday (apparently SQL rounds) 
select @end = dateadd(ms, -3, dateadd(day, 1, @start)) 

值将被

2015-02-04 00:00:00.000 
2015-02-04 23:59:59.997 

,你可以在这两个变量之间做了。由于您使用的是between,因此您需要考虑时间部分。您可以更改where子句去第二天,并在@end上进行独家检查

select @end = dateadd(day, 1, @start) 

where Evaluated >= @start and Evaluated < @end 
+0

我在运行时收到以下内容: Msg 156,Level 15,State 1,Line 2 关键字'current_date'附近的语法错误。 – Gareth 2015-02-05 19:51:20

+0

@Gareth,答案是MySQL。显然,MSSQL有点复杂。我用一个例子更新了它。 – Brandon 2015-02-05 20:24:36