Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return last inserted ID without using a second query

I'm working on an ASP.NET project (C#) with SQL Server 2008.

When I insert a row into a table in the database, I would like to get the last inserted ID, which is the table's IDENTITY (Auto Incremented).

I do not wish to use another query, and do something like...

SELECT MAX(ID) FROM USERS;

Because - even though it's only one query - it feels lame...

When I insert something I usually use ExecuteNonQuery(), which returns the number of affected rows.

int y = Command.ExecuteNonQuery();

Isn't there a way to return the last inserted ID without using another query?

like image 398
Ali Bassam Avatar asked Jan 12 '13 23:01

Ali Bassam


People also ask

How do I get last insert ID in SQL?

select last_insert_id (); Code language: SQL (Structured Query Language) ( sql ) As you can see clearly from the output, the LAST_INSERT_ID() function returns the generated value of the first row successfully inserted, not the last row.

Can select last_insert_ID() be used to return 0?

In the following instance, SELECT LAST_INSERT_ID (); can return 0, but it is a query problem and not a ProxySQL problem. It can also return the id of a previously successful insert within the current connection

How to get the ID of the last inserted/updated record?

If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately. In the table "MyGuests", the "id" column is an AUTO_INCREMENT field: CREATE TABLE MyGuests (.

Does MySQL last_insert_ID () return the last row successfully inserted?

As you can see clearly from the output, the LAST_INSERT_ID()function returns the generated value of the first row successfully inserted, not the last row. C) Using MySQL LAST_INSERT_ID()function in a stored procedure First, create two tables accountsand phonesfor testing:


1 Answers

Most folks do this in the following way:

INSERT dbo.Users(Username)
VALUES('my new name');

SELECT NewID = SCOPE_IDENTITY();

(Or instead of a query, assigning that to a variable.)

So it's not really two queries against the table...

However there is also the following way:

INSERT dbo.Users(Username)
OUTPUT inserted.ID
VALUES('my new name');

You won't really be able to retrieve this with ExecuteNonQuery, though.

like image 145
Aaron Bertrand Avatar answered Sep 28 '22 06:09

Aaron Bertrand