Click here to Skip to main content
15,890,897 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Is there a function I can use to retrieve the unique id (talking about primary key) of the last insertion into a table?


The issue is that I need to insert the ID of the last insertion as a reference ID in another table immediately.As it appears to me I may have to execute a select query to fetch this needed ID but that appears a waste of valuable time to me.
Posted

you can use IDENT_CURRENT function in sql server

SELECT IDENT_CURRENT('tableName')
 
Share this answer
 
Comments
Gbenbam 28-Feb-14 3:46am    
Pardon me.I am new to ADO.Could you show me how to do this with ado, particularly how to retrieve it from the record set (I suppose).
Gbenbam 28-Feb-14 3:51am    
I mean will the result be the first item in a field collection or what?
prakashdotnet 28-Feb-14 4:14am    
it returns single value from you table ,lets say your table has 5 record with latest identity 5 , then it return latest Identity value.
Hello ,

You can use SCOPE_IDENTITY() to get the latest Primary Key or Identity value.
try like this way
declare @id int
insert into tblname values(val1, val2)
select @id=SCOPE_IDENTITY()

thanks
animesh
 
Share this answer
 
Comments
Gbenbam 28-Feb-14 3:49am    
Pardon me, I am new to ado.How do I retrieve it from the record set.Will the result be the first item in a field collection or what?
Animesh Datta 28-Feb-14 3:55am    
it does not return any field collection , it only returns the last inserted primary key (a single value) .
The absolut best and fastes way to do this, is to use the OUTPUT clause
See here http://technet.microsoft.com/en-us/library/ms177564.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900