Home Forums SQL Server 2008 T-SQL (SS2K8) DateDiff help to verify my code is correct or not? RE: DateDiff help to verify my code is correct or not?

  • dhananjay.nagarkar (3/14/2013)


    Hi Sean,

    When you say-

    "

    I haven't seen all the other threads but from what you posted I can't figure out why you are using DATEDIFF at all. It doesn't meet your requirements and it will make your query nonSARGable"

    Can you please help me understand why it does not meet my requirement?

    Also Why and under what scenarios / situtations DateDiff function needs to be used and need not be used?

    The solution you and Lynnhave provided that I already had beven before I joined this site, but using Predicates comparison for dates is not allowed in my team I have been asked to use DateDiff hence would be much obliged if you can justiy your reason and help me learn please so that I can convince my manager 🙂

    Kind Regards

    Dhananjay

    SARGable, meaning SQL Server will use an index on the table if one exists that benefits the query. Using DATEDIFF the way you are using it will force SQL Server to use a table scan and process every row of the table(s) to determine if the criteria is met for the records to be included in the result set.

    As for what DATEDIFF will do, run the following:

    declare @Date1 datetime, @Date2 datetime;

    set @date1 = '20130314 19:23:30.000';

    set @date2 = '20130314 19:23:45.000';

    -- By observation @date1 is less than @date2

    select

    @date1,

    @date2,

    case when @date1 < @date2 then '@date1 < @date2' else '@date2 <= @date1' end, -- will display @date1 < @date2: true

    case when datediff(day,@date1,@date2) > 0 then '@date1 < @date2' else '@date2 <= @date1' end -- will display @date2 <= @date1: not true