views:

487

answers:

5

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.

+1  A: 

select scope_identity

insert into table values ('string value');select scope_identity()

Details here

gmcalab
Is that from: http://www.velocityreviews.com/forums/t303448-return-identity-after-sql-insert.html ? If so you should provide a link.
instanceofTom
+1  A: 

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() 
Adam Porad
A: 

In MySQL you can use LAST_INSERT_ID()

Brian Young
A: 

In SQL Server, you can also use the OUTPUT clause on your INSERT statement:

INSERT INTO Entrys('Name', 'Description') 
OUTPUT Inserted.EntryID
VALUES ('abc','xyz') 

This will output the newly created IDENTITY field value.

marc_s