SQL - Inserting a row and returning primary key
Solution 1:
For MS SQL Server:
SCOPE_IDENTITY()
will return you the last generated identity value within your current scope:
SELECT SCOPE_IDENTITY() AS NewID
Solution 2:
For SQL Server 2005 and up, and regardless of what type your primary key is, you could always use the OUTPUT
clause to return the values inserted:
INSERT INTO dbo.YourTable(col1, col2, ...., colN)
OUTPUT Inserted.PrimaryKey
VALUES(val1, val2, ....., valN)