【问题标题】:Parsing date in sql query在sql查询中解析日期
【发布时间】:2013-03-26 12:30:38
【问题描述】:

我使用的是 SQL Server 2005。

我的Trade_Date 列的数据类型为datetime

它的值为:2/12/2013 11:59:00 PM , 2/13/2013 11:59:00 PM

即不同的日期与时间。

我想比较 where 子句中的日期 [仅日期]。

我正在尝试以下查询:

select * 
from foclosing 
where CONVERT(varchar(11), Trade_Date) like '2/12/2013 %'

select * 
from foclosing 
where Trade_Date = CONVERT(datetime, '2/12/2013')

但是这两个查询都不起作用。

可能是什么问题?

【问题讨论】:

标签: sql sql-server-2005 datetime


【解决方案1】:
select * from foclosing
where Trade_Date >= '20130212' AND Trade_Date < '20130213'
  1. 使用对 SQL Server 安全的 yyyymmdd
  2. 不要将函数应用于列,然后比较(您的第一个查询)
    在此处查看错误 2:https://www.simple-talk.com/sql/t-sql-programming/ten-common-sql-programming-mistakes/
  3. 不要将基于语言环境的日期作为 varchar 进行比较(您的第一个查询)
  4. Trade_Date 有一个时间元素,这就是您的第二次查询失败的原因

总之,日期转换不应该用于这样的例子:datetime is a range

【讨论】:

  • 请在您的回答中提及: : SELECT * FROM foclosing WHERE CONVERT(VARCHAR(10), Trade_Date, 111) = convert(datetime,'2/12/2013')
  • @Freelancer:根据我的第二个要点,这是一个非常糟糕的模式
  • 哦..对不起,我认为这也是常规做法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 1970-01-01
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
相关资源
最近更新 更多