Get the resulting identifier from an insert

  • Thread starter Thread starter Ryan Taylor
  • Start date Start date
R

Ryan Taylor

Hello.

In my ASP.NET web application I need to be able to get the resulting ID from
an insert into a table immediately after the insert. There are no other
unique fields in the table to query against. The table would look like

tblUsers
-id
-first_name
-mid_name
-last_name
-date_created
-date_modified

I could get the last item inserted by date, but this assumes that other
records are not inserted between the first insert and the query for the last
item inserted. I could also, temporarily insert a GUID into one of the
fields, create the record, return the created ID and then repopulate the
table with the real values. But this seems like too many trips to the
database.

Is there a better way to accomplish this? Either in SQL or in C#?

I am using SQL Server 2000, C# and the SqlConnection, SqlCmd, SqlReader
objects.

Thanks.
 
Ryan,

You can query (or use an output parameter) for the SQL system
function/global variable @@IDENTITY to get the ID back from the last row
inserted.

I hope this helps
 
Back
Top