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 DateTime
values. 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.
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".
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.
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.
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.
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