Is there any way I can get the last inserted ID if I am using SQL Server CE? I have 2 tables and when a new record is created, I want to be able to save the ID in the second table too.
5 Answers
use this query:
INSERT INTO Persons (FirstName) VALUES ('Joe'); SELECT ID AS LastID FROM Persons WHERE ID = @@Identity; or you can view this link for more info: http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/
Comments
Assuming higher values of id are always newer, how about:
SELECT TOP 1 id FROM your_table ORDER BY id DESC or:
SELECT MAX(id) FROM your_table 2 Comments
Joel C
That doesn't account for possible concurrency issues. You're introducing a race condition, hoping your
SELECT MAX(id) is executed before another record gets inserted. I'd go with @@Identity since SCOPE_IDENTITY() isn't supported in SQL CE.Ash Burlaczenko
@@Identity assumes the select is run in the same session. It's not clear from the OP that is the case so I think this is the better answer for the information given.
This worked fine for me
SELECT TOP (1) your_id FROM your_table ORDER BY your_id DESC