DATEDIFF question

  • Is there a performance difference between these 2 calculations?

    IF DATEDIFF(SECOND,@StartDate,@EndDate) <0

    BEGIN...

    versus

    IF @StartDate >= @EndDate

    BEGIN...

    Both variables are datetime.

    __________________________________________________________________________________
    SQL Server 2016 Columnstore Index Enhancements - System Views for Disk-Based Tables[/url]
    Persisting SQL Server Index-Usage Statistics with MERGE[/url]
    Turbocharge Your Database Maintenance With Service Broker: Part 2[/url]

  • I'd say minimal difference, but I'd personally use the second option.

  • I agree with Lynn - I prefer the second method just because it is clearer what you are doing.

    Jeffrey Williams
    “We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”

    ― Charles R. Swindoll

    How to post questions to get better answers faster
    Managing Transaction Logs

  • Marios Philippopoulos (3/13/2009)


    Is there a performance difference between these 2 calculations?

    IF DATEDIFF(SECOND,@StartDate,@EndDate) <0

    BEGIN...

    versus

    IF @StartDate >= @EndDate

    BEGIN...

    Both variables are datetime.

    They are not logically equivalent tests. Notice the different results in the code below. There are other problems with using DATEDIFF for this; if the time difference it too large, you will will get an overflow. The version with DATEDIFF goes to a lot of work to produce incorrect results.

    declare @StartDate datetime,@EndDate datetime

    select @StartDate = '20090314 00:00:00.003', @EndDate = '20090314 00:00:00.000'

    IF DATEDIFF(SECOND,@StartDate,@EndDate) <0

    begin print 'true 1' end else begin print 'false 1' end

    IF @StartDate >= @EndDate

    begin print 'true 2' end else begin print 'false 2' end

    Results:

    false 1

    true 2

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply