SQL - Inserting a row and returning primary key

Samuel Moriarty picture Samuel Moriarty · Dec 12, 2011 · Viewed 75.7k times · Source

I have a little witty problem. Say, I inserted a row with some data in a table where a primary key is present. How would one "SELECT" the primary key of the row one just inserted?

I should have been more specific and mentioned that I'm currently using SQLite.

Answer

Michael Fredrickson picture Michael Fredrickson · Dec 12, 2011

For MS SQL Server:

SCOPE_IDENTITY() will return you the last generated identity value within your current scope:

SELECT SCOPE_IDENTITY() AS NewID