Get last record inserted without primary key or id

Sometimes we need to get the last record inserted into the database. But if there is no primary key, date, or ID field to query we can use a temp table to return the results we need.

Example:
Table MY_CONTACTS
contains
Contact varchar(100) not null
Note varchar(200) null

//select all records into a temp table
select IDENTITY(int,1,1) AS id, contact, note
into #tempContacts
from MY_CONTACTS
...
//get the last record
select * from #tempContacts
where id = @@identity
...
// pull all records to compare results.
select * from #tempContacts

Cup size   
Select size then click on coffee cup.
This entry was posted in Code, Snippets, SQL. Bookmark the permalink.