Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL datetime compare

I want to get some values from my table an there are some conditions about its datetime columns.

I want to get all hotel values of a stated city from my table, which is named "LocalHotels". Also I should declare two DateTimevalues. First value should be less than or equal to hotel's value in "start" column, which is datetime data type. Second value should be greater than or equal to hotel's value in "deadline" column, which is datetime data type, either.

All datetime values in these two columns are inserted in German CultureInfo format.

When I stated query below, there are no problems;

string query = "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='5.12.2015 00:00:00' AND deadline >='8.12.2015 00:00:00' ORDER BY city";

However when I changed day value of DateTime values from one digit to two digits, as I stated in below;

string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='15.12.2015 00:00:00' AND deadline >='18.12.2015 00:00:00' ORDER BY city"

I got an SQLException which indicates;

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

like image 847
Bernard Black the Second Avatar asked Dec 09 '15 08:12

Bernard Black the Second


People also ask

Can you compare DateTime 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 can I compare two date fields in SQL?

Here we will see, SQL Query to compare two dates. This can be easily done using equals to(=), less than(<), and greater than(>) operators. 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.

How can I compare date and DateTime in SQL Server?

To filter a table on a DATETIME column comparing only the date part, use CAST() only around the parameter, and >= and < with the desired date and the day after.


1 Answers

SELECT CONVERT(char(10), GetDate(),126)

or

select convert(varchar,getDate(),112)

or

select replace(convert(varchar, getdate(), 111), '/','-')

Test out the queries above to get the date in the desired format (replace GetDate() with your date, or dateColumn). As others pointed out you need the format YYYY-MM-DD.

like image 179
CM2K Avatar answered Sep 28 '22 09:09

CM2K