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 :)
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.
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".
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.
SELECT CASE WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) ...
Should do what you need.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With