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
  • 2
    what database are you using? SQL Server, MySQL, etc? Commented Dec 30, 2009 at 4:03

5 Answers 5

4

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() 
Sign up to request clarification or add additional context in comments.

Comments

4

select scope_identity

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

Details here

1 Comment

Is that from: velocityreviews.com/forums/… ? If so you should provide a link.
4

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.

1 Comment

If multiple VALUES tuples are specified, are returned IDs guarantee to be in the same order as the values tuples?
3

In MySQL you can use LAST_INSERT_ID()

Comments

0

As @marc_s said for SQL Server, in PostgreSQL you can obtain the same behaviour with:

INSERT INTO Entrys ('Name','Description')
VALUES ('abc','xyz')
RETURNING EntryID;

RETURNING is also really useful when you're inserting several tuples and you want all the generated IDs for each of the rows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.