script to find out last record inserted in the table

  • How to  find out last record inserted in the table

    Thanks

     

  • Do you have a column in the table that contains an inserted timestamp, or an increasing value like an Identity column ?

  • yes I have timestamp column in the tbl

  • Then things should be simple.

    (replace "table"  with the table name & "time stamp field" with the actual time stamp field name.

    select * from <table>

    where <time stamp field> =(select max(time stamp field) from table)

  • Hi

    I just recently had to work this out (moving website from MySQL to MS SQL and missing the last_insert_id ).

    I found this worked:

    SET NOCOUNT ON

        query_goes_here

    SELECT LAST_INSERT_ID=@@IDENTITY

    SET NOCOUNT OFF

    If you do a search, there is a reason for setting NOCOUNT off (I don't know why and I haven't tried without it so don't know if it's necessary).

    My impression is using the above is more reliable than getting the max insert id as there's always the (admittedly) minor chance of another insert within the same millisecond eeek

    Hope this helps.

    Regards, Alison

  • What if there is no identity column is the table...???

    Naveen

  • Then Steve Ballmer will come to your house and spank you!

     

    (Microsoft likes Identity columns. I don't know why they just do.)



    David W. Clary
    MCSD
    Data Miner 49er
    Sr. Database Administrator, Ceiva Logic

  • Setting nocount on means the results of your SELECT statement won't be returned as results of the procedure, they will just be used inside it.

Viewing 8 posts - 1 through 7 (of 7 total)

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