Home Forums SQL Server 2005 T-SQL (SS2K5) datetime => how to have complete date with 00:00:00.000 RE: datetime => how to have complete date with 00:00:00.000

  • Jeff Moden (4/7/2011)


    Either of the following is what I consider to be a "best practice". They're both very fast but the first one edges out the second when it comes to millions of rows if you need to apply it to something that large.

    SELECT CAST(DATEDIFF(dd,0,GETDATE()) AS DATETIME),

    DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)

    Replace the GETDATE() with whatever date you may have including dates in a column from a table. Just don't forget to add the FROM clause for the table. 😀

    Ah... I just had a horrible thought based on how the original question was posed. If you're trying to use such a thing as criteria for a JOIN or a WHERE clause, DO NOT use either of the two methods above on the COLUMN of a TABLE. Instead, do this...

    SELECT something

    FROM SomeTable

    WHERE SomeDateColumn >= SomeWholeDate

    AND SomeDateColumn < DATEADD(dd,1,SomeWholeDate)

    The code above finds all the rows in SomeTable that have a date (with or without time) that falls on SomeWholeDate and it does so while still allowing an index on SomeDateColumn to be used. Using just about any formula on SomeDateColumn itself will prevent the use of an index.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)