How to gei Last ID
am 18.04.2008 14:26:10 von MarkoWhen 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
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
select @@identity
or
select scope_identity()
"Marko"
news:fua46k$8qd$1@sunce.iskon.hr...
> 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
>
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
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"
news:fua46k$8qd$1@sunce.iskon.hr...
> 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
>
> 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(