Keagan Ladds
Keagan Ladds

Reputation: 458

View SQL entries that were entered within past 24 hours

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

Answers (2)

JNK
JNK

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

user806549
user806549

Reputation:

SELECT * FROM DataTable WHERE [DATE] > getdate() - 1

Upvotes: 2

Related Questions