Remove Time from DateTime

  • What is the difference between these 2 lines in SQL Server 2005 Express?

    DATEADD(d, 0, DATEDIFF(d, 0, @Today));

    and

    DATEADD(d, DATEDIFF(d, 0, @Today), 0);

    Other than making this statement fail at random times:

    DECLARE @DateSrc DATETIME;

    -- Chop off the time part:

    SET @DateSrc = DATEADD(d, 0, DATEDIFF(d, 0, @Today));

    INSERT INTO dbo.SeqNo(MyGUID, TheDay, LastNo)

    SELECT @MyGUID, @DateSrc, 0

    WHERE NOT EXISTS (

    SELECT 1 FROM dbo.SeqNo AS sn

    WHERE sn.MyGUID = @MyGUID AND sn.TheDay = @DateSrc

    );

  • In the DateAdd function, third parameter is date. 2nd parameter is the increment.

    When you write DATEADD(d,0,getdate())

    0 days are added to current date.

    When you write DATEADD(d, DATEDIFF(d, 0, @Today), 0);

    the date here is 0, select cast(0 as datetime) -- 1900-01-01 00:00:00.000

    I'm not sure what you are trying to achieve here.

    https://sqlroadie.com/

  • What I was trying to achieve was to work out why the insert created the exception below every now and again and the initial analysis pointed to the DATEADD format but ended up being more complicated.

    System.Data.SqlClient.SqlException (0x80131904): Violation of UNIQUE KEY constraint. Cannot insert duplicate key in object.

    The end result was as follows:

    1) Both of the DATEADD method formats produce the exact same result, so you can use either, but the 0 as date argument "feels" better.

    2) The WHERE NOT EXIST does not guarantee (no atomic action) that the condition DOES NOT EXIST as the thread can be interrupted in between the select and the insert, which creates the exception.

    3) Always double and triple check the calling code to make sure that it's not calling the SQL without wrapping the code in an exception and trying again WHEN it fails if needs be. In this case, I just needed to ignore the exception.

    One thing I must say, it was a very interesting learning exercise.

Viewing 3 posts - 1 through 2 (of 2 total)

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