Get row where datetime column = today - SQL server noob

后端 未结 5 818
旧巷少年郎
旧巷少年郎 2020-12-03 04:32

In sql 2005, instead of building a query from dateparts year, month and date,

is there an more succinct way of writing the where clause?

5条回答
  •  有刺的猬
    2020-12-03 05:16

    On SQL Server 2008, you would have a new DATE data type, which you could use to achieve this:

    SELECT (list of fields)
    FROM dbo.YourTable
    WHERE dateValue BETWEEN 
       CAST(GETDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE))
    

    The CAST(GETDATE() AS DATE) casts the current date and time to a date-only value, e.g. return '2010-04-06' for April 6, 2010. Adding one day to that basically selects all datetime values of today.

    In SQL Server 2005, there's no easy way to do this - the most elegant solution I found here is using numeric manipulation of the DATETIME to achieve the same result:

    SELECT (list of fields)
    FROM dbo.YourTable
    WHERE dateValue BETWEEN 
       CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME) AND 
       DATEADD(DAY, 1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
    

提交回复
热议问题