Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Get the Record Id after inserting a new record

Author  Topic 

tyh2003
Starting Member

3 Posts

Posted - 2009-03-19 : 03:12:02
I have a table its primary key is set to be auto increment, when i insert a new record,how could i obtain the id corresponding to the new record in just one sql command execution??


thks in advance

senthil_nagore
Master Smack Fu Yak Hacker

1007 Posts

Posted - 2009-03-19 : 03:15:49
Use SCOPE_IDENTITY() Function

insert into table(...)
@id=scope_identity()

Select @id

Regards

Senthil.C
----------------------------------------------------------------------------
Server: Msg 3902, Level 16, State 1, Line 1
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-03-19 : 11:04:09
quote:
Originally posted by senthil_nagore

Use SCOPE_IDENTITY() Function

insert into table(...)
set @id=scope_identity()

Select @id

Regards

Senthil.C
----------------------------------------------------------------------------
Server: Msg 3902, Level 16, State 1, Line 1
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.


Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-03-19 : 11:07:44
also see
http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
Go to Top of Page
   

- Advertisement -