Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL compare dates?

I have 2 dates (datetimes):

date1 = 2010-12-31 15:13:48.593
date2 = 2010-12-31 00:00:00.000

Its the same day, just different times. Comparing date1 and date2 using <= doesnt work because of the date1 time. So date1 <= date2 is wrong, but should be true. Can I compare them by just looking at the year, month and day so they are the same? Its SQL Server 2008.

Thanks :)

like image 291
grady Avatar asked Jan 25 '11 13:01

grady


People also ask

How compare dates in MS SQL Server?

In SQL, the date value has DATE datatype which accepts date in 'yyyy-mm-dd' format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement. We can declare variables easily by using the keyword DECLARE before the variable name.

Can you compare dates in SQL?

The right way to compare date only values with a DateTime column is by using <= and > condition. This will ensure that you will get rows where date starts from midnight and ends before midnight e.g. dates starting with '00:00:00.000' and ends at "59:59:59.999".

How do you check if one date is greater than another in SQL?

In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a 'YYYY-MM-DD hh:mm: ss. mmm' pattern.


1 Answers

SELECT CASE WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) ... 

Should do what you need.

Test Case

WITH dates(date1, date2, date3, date4)      AS (SELECT CAST('20101231 15:13:48.593' AS DATETIME),                 CAST('20101231 00:00:00.000' AS DATETIME),                 CAST('20101231 15:13:48.593' AS DATETIME),                 CAST('20101231 00:00:00.000' AS DATETIME)) SELECT CASE          WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) THEN 'Y'          ELSE 'N'        END AS COMPARISON_WITH_CAST,        CASE          WHEN date3 <= date4 THEN 'Y'          ELSE 'N'        END AS COMPARISON_WITHOUT_CAST FROM   dates  

Returns

COMPARISON_WITH_CAST   |  COMPARISON_WITHOUT_CAST Y                         N 
like image 54
Martin Smith Avatar answered Sep 19 '22 10:09

Martin Smith