How to get the Last record?

  • Hai,

    I want to get the last inserted record from the table.

     

    Note:

    Table not having identity and timestamp columns.

    Thanks.

    Regards,

    AMI.HANEES.

     

     

  • There is no such thing as first, or last, or second, etc rows in relational model.

    All rows are equal in their rights.

    If you need to keep the record of time moment the row was inserted/updated just do it.

    Create a new column with DEFAULT = GETDATE() or create separate log table keeping the times when your rows have been inserted.

    _____________
    Code for TallyGenerator

  • Unless you store a datetime when the record is inserted, I'm afraid it looks as though the information is not represented in your data.

    Tim Wilkinson

    "If it doesn't work in practice, you're using the wrong theory"
    - Immanuel Kant

  • A common misconception is people thinking that SQL Server works similarly to file-system based databases such as FoxPro/DBase which have the concept of row numbers and traversing a table in index order.  SQL Server, as others have said, is relational - all rows are equal.

    Having said that, you could obtain the last inserted row in your table without needing to add a datetime or identity column (although I would suggest that these are the better way to go - you can set default value for the datetime so that you needn't specify it in insert statements).  To do this without adding columns you'll need to create a trigger for insert on the table.  This trigger will update another table which will only ever have 0 or 1 rows - the contents of the table will be the last inserted value into your table of interest.  As you can see, this is not obvious (the presence of triggers and their side effects is not easily observed) nor is it the best way to go.  But it will allow for your requirement to get the last inserted value without needing datetime (note that SQL timestamp is different) nor an indentity col.

    Last question: What is your primary key?  Does it increment in a predictable way?  Perhaps a create table statement and some sample data could help us advise you further.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply