Retrieving the auto-generated number

Posted on 2001-09-04
Last Modified: 2007-12-19
Hi geeks,

Actually I'm quite new to this, so your patience is much appreciated.

When inserting certain record that has a field as auto-generated number, one may need to return this number for later association with other records in other tables.  For example; sometimes it's impossible to distinguish the record except from this number, so if inserted, there will be no way to get back to the record unless this auto-generated number is captured right after the insertion process.

In oracle, (I don't know really if it's oracle specific or not!) I found that they provide some sort of routine(maybe it's pl/sql, I don't know) on which you can invoke ".nextval" to insert the result as an ID to the record, then invoke ".currval" to get that ID for programming use.  Frankly, I don't know if I can do such thing in MS SQL server or even how to do it, so I appreciate if you can help me in this.

I saw somewhere else that after insertion of certain record they do something like:

"SELECT @@identity"

I really don't know how such thing works, or even if it could be used in MS SQL server, but I'm in favor of using such thing (or at least that what I feel from the syntax), because when dealing with concurrent invocations to database, one user may insert a record using
"recordnum.nextval" for example, and during insertion process, another may insert another record before the first has finished, so if the first one invokes
"recordnum.currval" he will take the wrong ID.

To brief, I have two questions:

1. Can we use [routine].nextval in MS SQL server? If so, is it safe to use it (see case above)? If yes, can you please tell me how [routine] can be created in MS SQL server.

2. Is there anything called "SELECT @@identity" in MS SQL server? Do I need special instructions when creating the database to be able to use it, like saying: "set this field as identity or auto number, etc."? Does it suffer from the concurrent invocation problem exists in case of [routine].nextval?

Thank you very much for your help.

Question by:ymasri
  • 3
  • 2

Expert Comment

ID: 6452590
Hi ymasri@idg,
 @@IDENTITY is a global variable, which holds the last inserted identity (auto-generated number) for the last insert. you can assign in a viariable and it is valid unitil the next autogenerated insert. So for example if you have the code:

create table tst (id int identity (1,1), val varchar(10) )

delcare @lastid int
insert inot tst (val) ('val1')
insert inot tst (val) ('val2')
set @lastid=@@IDENTITY
print @lastid

lastid variable will be 2, but not one


Expert Comment

ID: 6452595
there is no function or stored procedure or like in oracle - sequences - to do this job. if you want you can write your own. however the best and safest method is to use the identity property of the field and use @@IDENTITY variable.

Author Comment

ID: 6452686
Thank you ibro for your response.

Forgive my ignorance, but what does it mean to say identity(1,1)? It sounds something like declaring the "id" as an identity, but I don't know what is it to say "(1,1)"?

You didn't address the problem of concurrent invocation of the database, I think with using @@IDENTITY, the problem still exists.  Isn't there any solution from the database view?
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.


Accepted Solution

ibro earned 75 total points
ID: 6452809
identity (1,1) means that the field will be auto-numbered starting with 1 and increasing each next record with 1.
so the first value will be 1, next 1+1, and so on.
example identity(100,5) means that first value will be 100, next 105, them 110 and so on.
SQL server is taking care of concurent invocatio of insert. It applies row-level (sometimes table-level) locking, so it garantee that there will be no duplicate values. @@IDENTITY variable keeps the last generated identity value for the current connection, but not for all connections.

Expert Comment

ID: 6452918
Well, for the control over concurrent invocations, SQL Server, as well as Oracle both do more than just a "control" ;) ( wink ) If 2 users insert 2 records and the insert is too close in time or if some really neat trick is needed, like generate and retrieve the @@identity / sequence while insert is in progress, it will return a run time error and a message, message reads, identity undefined. On the other hand, identity is a function that can be used in a select list to generate values for an insert into for example temp table. There are restrictions applied onto table/column that hold identity values, there can be only 1 column per table holding identity values. That can be serious limitation if you insert result of a complex join into a temp table, where one of the clummns is an identity in the base table, and need to rank the rows using identity function as a  value in a select list.
--- begin SQL pseudo code
identity( int, 0, 1 ), --- try to rank on teh fly
into #temp_table
table_1 as t1
inner join
table_2 s t2 on t1.ID = t2.ID_ref
inner join
table_3 as t3 on t3.ID_ref = t2.ID
where name like '%foo%'
order by, t1.PK_base_table_idemtity desc

 The statement will fail with error. Error message reads ( in - exact ) only one identity column allowed per table. In all other respects - which sufficses 99.9999 of normal database life identity works perfect. By the way in the SQL Server 2000 a great wealth of functions appeared that makes identity even more robust. IDENT_CURRENT() retrieves last identity generated for a particular table IDENTITY_SCOPE will return identity generated in current block of Transact SQL code.

Author Comment

ID: 6453158
Thank you miron for your contribution, I'm sure it's a reliable solution that works 99.9999% of the cases.

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
I have a large data set and a SSIS package. How can I load this file in multi threading?
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how the fundamental information of how to create a table.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question