Reputation: 458
I am trying to view the entries into my sql database that were entered within the last 24 hours. My database has a Date and Time field that are set when the record is entered. I am currently using the following code but it is not working. The is code executed correctly so I suspect that my SQL query is incorrect.
DateTime Time = DateTime.Now;
Time = Time.Subtract(new TimeSpan(24, 0, 0)); //Get DateTime of 24 Hours Ago
SqlDataSource1.SelectCommand = "SELECT * FROM DataTable WHERE Date>'" + Time.ToShortDateString() + "' AND Time>'" + Time.ToShortTimeString() + "'";
My Table name is correct and the field names are correct.
Thanks
Upvotes: 1
Views: 211
Reputation: 65157
You need to delimit your field names since they are reserved keywords:
SqlDataSource1.SelectCommand =
"SELECT * FROM DataTable WHERE [Date]>'" + Time.ToShortDateString() + "' AND [Time]>'" + Time.ToShortTimeString() + "'"
This is a very good reason to choose field names that are not reserved words in SQL.
If these are both one field, then you can just do a single evaluation of Date and Time:
WHERE <datetime field name> > GetDate() - 1
Upvotes: 2