To get date from datetime in sql

前端 未结 5 1213
醉话见心
醉话见心 2020-12-20 07:44

I have datecreated field in a table. It contains value as \"2009-12-30 11:47:20:297\" I have a query like this:

select * 
  from table 
 where          


        
5条回答
  •  旧巷少年郎
    2020-12-20 08:03

    The datetime field includes both the date and the time, accurate to the millisecond. Your query will only work if it is the exact millisecond stored in the database.

    To check if it is today, but ignore the time of day, you can check for a range like this:

    select * from table where
    DateCreated >= '2009-12-30' and
    DateCreated < '2009-12-31'
    

    You can use that in conjunction with a function that converts the current date, as astander or Khilon has posted. Here is a full example using astander's answer. Also, as Craig Young points out, this will work with indexes.

    select * from table where
    DateCreated >= DATEDIFF(dd,0,GETDATE()) and
    DateCreated < DATEDIFF(dd,0,GETDATE())
    

提交回复
热议问题