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?
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.
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
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 (.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With