Rocshy
Rocshy

Reputation: 3509

Get last inserted id

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

Answers (5)

Geno
Geno

Reputation: 11

This worked fine for me

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

Upvotes: -1

ron tornambe
ron tornambe

Reputation: 10780

SELECT @@IDENTITY

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

Upvotes: 13

Aboodred1
Aboodred1

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

Brissles
Brissles

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

Raphaël VO
Raphaël VO

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

Related Questions