How to return the last entered item?
I am trying to get the last entry from my database based off the date entered. The sql is not working exactly as I want it. Here is my sql
SELECT TOP 1 * FROM BILLS_HITS ORDER BY DATETIMEADD DESC
Can anyone see anything wrong with it? The sql returns a record with the date - "6/6/2012 7:10:11 AM" and not one that is for 6/10/2012.
Use a more database-agnostic approach:
SELECT * FROM BILLS_HITS WHERE DATETIMEADD = (SELECT MAX(DATETIMEADD) FROM BILLS_HITS)
The TOP keyword is more specific to MSSQL, while the above query would work in most other DBMSs including MSSQL.
Also, to make the selection fast, you'll likely want to put an index on the column DATETIMEADD
If it doesn't work, make sure the DATETIMEADD column is of a proper date/datetime type and not just a varchar/char/text string.