0

Get the last record from a Microsoft SQL database table using ASP.net (VB) onto a web form.

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
Ralph08
  • 1
  • 1
  • 1

3 Answers3

1

Here is a basic solution:

var order = (from i in db.orders
             where i.costumer_id.ToString() == Session["costumer_id"]
             orderby i.order_id descending
             select i).Take(1).SingleOrDefault();
honk
  • 9,137
  • 11
  • 75
  • 83
Engin K.
  • 39
  • 5
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
  • @Matias then you need refactoring – ariel May 10 '11 at 08:38
  • @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
  • Right, but, what about other kinds of PK? – Matías Fidemraizer May 10 '11 at 08:43
  • 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