Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL INSERT INTO returning autoincrement field

I'm a long time desktop app C++ programmer new to SQL. I need to insert into a table with an autoincrment field, and have that sql statement return the new value for the autoincrement field.

Something LIKE:

INSERT INTO Entrys ('Name','Description')
VALUES ('abc','xyz')
SELECT Entrys.EntryID WHERE EntryID=[THE ONE JUST INSERTED!]

Sorry for being a noob.

like image 998
Joshua Avatar asked Dec 30 '09 03:12

Joshua


1 Answers

Assuming that you're using SQL Server, you can use scope_identity to return "the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch."

INSERT INTO Entrys ('Name','Description') VALUES ('abc','xyz');
SELECT SCOPE_IDENTITY() 
like image 75
Adam Porad Avatar answered Oct 05 '22 20:10

Adam Porad