Get the last record from a Microsoft SQL database table using ASP.net (VB) onto a web form.
Asked
Active
Viewed 3,920 times
0
-
1you haven't tried doing it, have you? – ariel May 10 '11 at 08:33
-
Challenge accepted, this sounds exciting! – Tom Gullen May 10 '11 at 08:35
-
Please provide more details as your question is not clear. – Muhammad Akhtar May 10 '11 at 08:37
-
oh how I wish I could vote to close... we really need the ability to stamp on rudimentary questions like this :( – Terry_Brown May 10 '11 at 08:42
3 Answers
1
I'm assuming he's trying to retrieve the last inserted record. As Ariel pointed out, the question is rather ambiguous.
SELECT TOP 1 * FROM Table ORDER BY ID DESC
If you have an identity column called ID, this is easiest. If you don't have an identity PK column for example a GUID you wont be able to do this.

Tom Gullen
- 61,249
- 84
- 283
- 456
-
And what happens if ID isn't autonumeric, or if it's not numeric at least? – Matías Fidemraizer May 10 '11 at 08:37
-
-
@ariel haha, you need to refactor a DB because you need to get latest added record? I'd prefer a timestamp instead of that. – Matías Fidemraizer May 10 '11 at 08:39
-
He should have a PK identity column. If he doesn't he should add one in probably. – Tom Gullen May 10 '11 at 08:39
-
-
Matias: http://stackoverflow.com/questions/932913/when-having-an-identity-column-is-not-a-good-idea – ariel May 10 '11 at 08:45
-
@Matias, how are we meant to know anything when the original question is so vague? Your criticism of my answer can equally be applied to your criticism. We don't know. This is one correct solution. Who cares, OP probably wont be reading it anyway. – Tom Gullen May 10 '11 at 08:46
-
I'm pretty sure he is not talking about a many to many relationship table. On that case only a timestamp would work. – ariel May 10 '11 at 08:47
-
@Matias I'm also keenly waiting for your answer that takes all the unknowns into account! – Tom Gullen May 10 '11 at 08:49
-
1@Tom Guillem, relax... I was kidding with @ariel. It's not criticism, I was just asking you what would happen if this isn't auto-numeric. In terms of objectivity, then, if you don't know how's his database, then why you think it has an autonumeric PK? But I repeat, don't mind it was criticism, it was just a suggestion!! – Matías Fidemraizer May 10 '11 at 09:01
0
You need to be more specific with actually putting it onto a web form, but the SQL to get the last record is:
SELECT *
FROM TABLE_NAME
WHERE ID = (SELECT MAX(ID) FROM TABLE_NAME)
Where ID is your ID and TABLE_NAME is your table name.

Andy Jones
- 829
- 11
- 14