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
 SQL Server 2000 Forums
 Transact-SQL (2000)
 get correct id from db

Author  Topic 

dev45
Yak Posting Veteran

54 Posts

Posted - 2004-09-29 : 05:22:58
hi all
suppose we have the following table
create table A([id] int identity(1,1), [data] varchar(10))

everytime a new insertion is done, a new [id] is created which i want to retrieve in the next sql statement. So i would have
=======================================
declare @id int
insert into A ([data]) select 'some data'
--(which will produce let's say id = 234)
select @id = max(id) from A
=======================================
how can i be sure that the returned value is 234 ?
if another user makes a simultaneous (a few milliseconds after mine) insert isn't it possible to (erroneously) retrieve id 235 ?
is there a way to 'lock' the table ?

mwjdavidson
Aged Yak Warrior

735 Posts

Posted - 2004-09-29 : 05:35:31
As it's an identity column, you can use @@identity, SCOPE IDENTITY, or IDENT CURRENT, depending on the specific circumstances. Look them up in BOL.

Mark
Go to Top of Page

dev45
Yak Posting Veteran

54 Posts

Posted - 2004-09-29 : 07:22:58
thx mark;)
scope_identity does the trick
Go to Top of Page

mwjdavidson
Aged Yak Warrior

735 Posts

Posted - 2004-09-29 : 07:25:22
no probs

Mark
Go to Top of Page
   

- Advertisement -