Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to gei Last ID

0 views
Skip to first unread message

Marko

unread,
Apr 18, 2008, 8:26:10 AM4/18/08
to
When I write new record with INSERT INTO i need to get ID (Autonumber, key
of this table) from this, just written record. How to do that in ASP.NET (VB
or C#) and SQL Server?

Thanks


Marc Gravell

unread,
Apr 18, 2008, 8:32:56 AM4/18/08
to
How are you doing the INSERTs? Basically, you just want to look at
SCOPE_IDENTITY() immediately after the INSERT; you could SELECT it, you
could RETURN it, or you could SET it into an OUT variable (I favor the
latter). In older versions of SQL-Server, @@IDENTITY is a fallback, but
suffers with triggers.

Marc

Microsoft Newsserver

unread,
Apr 18, 2008, 8:29:19 AM4/18/08
to

select @@identity

or

select scope_identity()


"Marko" <mar...@hotmail.com> wrote in message
news:fua46k$8qd$1...@sunce.iskon.hr...

Cowboy (Gregory A. Beamer)

unread,
Apr 18, 2008, 10:29:44 AM4/18/08
to
In general, this is easiest when you use stored procedures, although you can
batch commands with a semi-colon (;). I would not use @@IDENTITY, as you can
end up with the wrong value on a highly used system. SCOPE_IDENTITY() is
better.

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://gregorybeamer.spaces.live.com/lists/feed.rss

or just read it:
http://gregorybeamer.spaces.live.com/

*************************************************
| Think outside the box!
|
*************************************************


"Marko" <mar...@hotmail.com> wrote in message
news:fua46k$8qd$1...@sunce.iskon.hr...

Marc Gravell

unread,
Apr 18, 2008, 10:37:50 AM4/18/08
to
> I would not use @@IDENTITY, as you can
> end up with the wrong value on a highly used system.

This is misleading; high usage doesn't impact @@IDENTITY; @@IDENTITY is
limited to the current spid, but problems arise if an INSERT trigger
does one-or-more INSERTs - as you get the last identity on the spid,
which might be frmo an audit table. SCOPE_IDENTITY() resolves this by
getting the last identity (on the spid) for the current context - i.e.
the INSERT you just performed.

High usage does, however, affect IDENT_CURRENT(<table name>) - but this
should not really be used in transactional code - just from maintenance
scripts etc.

Marc

Cowboy (Gregory A. Beamer)

unread,
Apr 18, 2008, 11:32:33 AM4/18/08
to
Not trying to mislead, so thanks for the input. I have added that to my
knowledge base.

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

*************************************************
| Think outside the box!
|
*************************************************

"Marc Gravell" <marc.g...@gmail.com> wrote in message
news:%23B8zIHW...@TK2MSFTNGP05.phx.gbl...

0 new messages