user2575502
user2575502

Reputation: 703

How to compare date in SQL Server

I got 2 date strings and want to compare them in SQL Server like this:

if (convert(timestamp, '6/26/2017 2:07:15.197737 PM') = 
      convert(timestamp, '6/26/2017 2:07:15.187737 AM'))
    print 'y'
else 
    print 'n'    

Obviously, one date is PM and one date is AM, so they are different, but 'y' is printed out, can someone tell me how to compare this kind of date in SQL Server?

Upvotes: 0

Views: 154

Answers (2)

Jason A. Long
Jason A. Long

Reputation: 4442

If all you want to do is the comparison, the CHECKSUM function is a solid choice.

IF CHECKSUM('6/26/2017 2:07:15.197737 PM') = CHECKSUM('6/26/2017 2:07:15.187737 AM')
print 'y'
else 
print 'n'

or, give the date/time values you have displayed (higher resolution than DATETIME could accurately compare), you could CAST or CONVERT to DATETIME2(7)

if( convert(DATETIME2(7),'6/26/2017 2:07:15.197737 PM') = convert(DATETIME2(7),'6/26/2017 2:07:15.187737 AM'))
print 'y'
else 
print 'n'

Upvotes: 2

Squirrel
Squirrel

Reputation: 24763

if you want exact comparision including time

datetime_column1 = datetime_column2

if only compare by date only, convert it to date and compare

convert(date, datetime_column1) = convert(date, datetime_column2)

Upvotes: 0

Related Questions