Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Remove Time from DateTime Expand / Collapse
Author
Message
Posted Friday, February 8, 2013 2:49 PM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Sunday, March 17, 2013 10:06 PM
Points: 28, Visits: 86
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
);

Post #1417914
Posted Thursday, March 7, 2013 3:28 AM


SSC-Addicted

SSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-AddictedSSC-Addicted

Group: General Forum Members
Last Login: Tuesday, December 2, 2014 11:59 PM
Points: 406, Visits: 780
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.
Post #1427876
Posted Thursday, March 7, 2013 5:05 PM
SSC Rookie

SSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC RookieSSC Rookie

Group: General Forum Members
Last Login: Sunday, March 17, 2013 10:06 PM
Points: 28, Visits: 86
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.
Post #1428328
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse