Get the last inserted row ID (with SQL statement) [duplicate]

If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()

This works as long as you haven’t inserted another row – it just returns the last IDENTITY value handed out in this scope here.

There are at least two more options – @@IDENTITY and IDENT_CURRENT – read more about how they works and in what way they’re different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

Leave a Comment