Link to home
Start Free TrialLog in
Avatar of hrvica5
hrvica5Flag for Croatia

asked on

SQL

Hi,

How to select Last inserted ID ?

'Select * from table where'' last inserted id???

thx
Avatar of VipulKadia
VipulKadia
Flag of India image

If ID column is Unique ID then you can get last inserted id using @@IDENTITY.
Avatar of hrvica5

ASKER

yes id is unique

how?
Avatar of Éric Moreau
just after the insert statement, you can use SELECT SCOPE_IDENTITY()

if not, you will have to use: select max(ID) from table
ASKER CERTIFIED SOLUTION
Avatar of DavidMorrison
DavidMorrison
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
actually, @@identity is only to be used when
1) you are using SQL 7
2) you are in the same session that the one that did that "last insert"

for sql 2000 and later, you shall use SCOPE_IDENTITY() , but 2) above still applies.

so:

INSERT INTO yourtable ( col1, col2... ) VALUES ( 1,2, ... )
SELECT * FROM yourtable WHERE ID_col = @@identity -- sql 7
SELECT * FROM yourtable WHERE ID_col = SCOPE_IDENTITY() -- sql 2000+

note: while the function @@identity still exists in sql 2000+, it does though refer to the last identity value generated, which might not be the table you inserted into, but generated by a insert that is run by a trigger on the table you inserted to ...

to conclude: if you want to get the last generated record, even if the application did not do the insert itself:

select * from yourtable where id_col = ( Select max(id_col) from yourtable )
or
select top 1 * from yourtable order by id_col desc

hope this clarifies