4

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 5

13
SELECT @@IDENTITY 

will retrieve the last auto-generated identity value in SQL Server.

Sign up to request clarification or add additional context in comments.

Comments

5

I hope this example will help you.

INSERT INTO jobs (job_desc,min_level,max_level) VALUES ('A new job', 25, 100); SELECT job_id FROM jobs WHERE job_id = @@IDENTITY; 

Comments

1

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

1

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

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.
@@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.
-1

This worked fine for me

SELECT TOP (1) your_id FROM your_table ORDER BY your_id DESC 

2 Comments

This may work but it is much slower than the approved answer.
Also, I think this won't account for possible concurrency issues, like that stated in the first comment in Brissles's answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.