Reputation: 3509
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.
Upvotes: 4
Views: 9760
Reputation: 11
This worked fine for me
SELECT TOP (1) your_id FROM your_table ORDER BY your_id DESC
Upvotes: -1
Reputation: 10780
SELECT @@IDENTITY
will retrieve the last auto-generated identity value in SQL Server.
Upvotes: 13
Reputation: 1503
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;
Upvotes: 5
Reputation: 3881
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
Upvotes: 1
Reputation: 2630
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/
Upvotes: 1