【问题标题】:Find all rows where date column has timestamp = 00:00:00.000查找日期列时间戳 = 00:00:00.000 的所有行
【发布时间】:2019-08-26 06:23:08
【问题描述】:

我有一个表,其中一列作为registrationDate,其类型是日期时间。我需要找到所有registrationDate作为时间戳为00:00:00.000的行。 例如:

registrationDate: '2019-03-20 00:00:00.000'

我需要查询类似如下的内容:

select * from table where registrationDate like '%00:00:00.000';

【问题讨论】:

  • 请不要将日期时间值视为字符串。它们不是字符串,LIKE 将不起作用(我相信您已经尝试过)。您要查找的是具有午夜时间分量的数据。
  • (我在this post谈过这个。)

标签: sql sql-server tsql date datetime


【解决方案1】:

您可以将日期时间转换为时间:

WHERE CAST(registrationDate AS TIME) = '00:00'

【讨论】:

  • @GeorgeMenoutis 你不能使用 0。什么是 0 时间?试试吧。不管你怎么做,它都不会转换。
  • @Sean Lange 我在考虑底层数据类型。这:select case when convert(datetime,'19000101')=0 then 1 else 0 end 返回 1。但是在您发表评论后,我检查了转换表并注意到虽然从数字数据类型到 datetime 的转换可以显式和隐式地转换,但根本不可能转换到 time。每天都能学到新东西。
  • 是的,日期和时间数据类型的隐式转换是如此不同。
  • 分老类型(datetime/smalldatetime)和2008年引入的新类型(date/time/datetime2/datetimeoffset)。后者继承了很少的隐式行为(最常见的问题是 getdate()+1sysdatetime()+1)。
【解决方案2】:
WHERE registrationDate = CONVERT(date, registrationDate);

【讨论】:

【解决方案3】:

请参阅下面的更新

Create Table #tbl
(
registrationDate Datetime
)
Insert Into #tbl Values
('2019-03-20 00:00:00.000'),
('2019-03-20 00:00:25.000')

查询

Select * From #tbl
Where Cast(registrationDate As Time) = '00:00:00.0000000'

结果:

registrationDate
2019-03-20 00:00:00.000

更新:如果你真的需要使用“Like”

Select * From #tbl
Where convert(VarChar(50), registrationDate, 121) Like '%00:00:00.000'

【讨论】:

    【解决方案4】:
    select * from table where FORMAT(registrationDate, 'HH:mm:ss:ms') ='00:00:00.000'
    

    【讨论】:

    • FORMAT() 实际上是a pretty bad idea,尤其是作为扫描整个表的一部分。
    【解决方案5】:

    以下表达式为每个日期时间值获取相应的日期和时间部分:

    dateadd(day, datediff(day, 0, '<date_time>'), 0)
    

    因此,以下将完成这项工作:

    create table foo (id int, registrationDate datetime)
    insert foo values
       (1, '2019-04-04T03:22:48.00'),
       (2, '2019-04-04T00:00:00.00')
    select * from foo
    where registrationDate =
          dateadd(day, datediff(day, 0, registrationDate), 0)
    

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多