Finding last inserted row id

Posted by Parimi.chowdary under Sql Server on 10/18/2011 | Points: 10 | Views : 5173 | Status : [Member] | Replies : 5
How to find the last inserted record id in SQL Server




Responses

Posted by: Hmanjarawala on: 10/18/2011 [Member] Bronze | Points: 25

Up
0
Down
if record id is identity field then from @@Identity variable you ll get last id

Himanshu Manjarawala
Sr. Software Engineer@AutomationAnywhere
http://fieredotnet.wordpress.com/

Parimi.chowdary, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ndebata on: 10/18/2011 [Member] Starter | Points: 25

Up
0
Down
Sometime @@identity may not give you the correct result , in case some insert is going on a different table
You can use SCOPE_IDENTITY() function just after the insert statement go get the new identity value.

Parimi.chowdary, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Niladri.biswas on: 10/19/2011 [Member] Platinum | Points: 25

Up
0
Down
Also you can use
Output.Inserted


Best Regards,
Niladri Biswas

Parimi.chowdary, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sriramnandha on: 10/27/2011 [Member] Starter | Points: 25

Up
0
Down
Code:SELECT TOP 1 Id FROM Table1 ORDER BY Id DESC
solution2-

Code:
SELECT MAX(Id) FROM Table1


Hope This will Hep

Let me know any questions..

Regards
Sriram.R

sriram

Parimi.chowdary, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sriramnandha on: 10/27/2011 [Member] Starter | Points: 25

Up
0
Down
CREATE TABLE dbo.tracking0
(
userID INT IDENTITY(1,1)
PRIMARY KEY CLUSTERED,
username VARCHAR(32)
)
GO

Then, to get the "last" row:

SELECT userID, username
FROM dbo.tracking0
WHERE userID =
(
SELECT MAX(userid)
FROM dbo.tracking0
)


sriram

Parimi.chowdary, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response