SQL SERVER 2008 GET LAST INSERTED VALUES
Asked Answered
A

5

5

This is my table.

Ticket(id int auto_increment,name varchar(50));

after inserting into this table i want send id and name to mail.. how can i get the last Inserted value.

help to solve this...

Antoninaantonino answered 25/9, 2012 at 11:21 Comment(0)
M
10

Look into: Scope_identity

SCOPE_IDENTITY()

The table which is having Identity Property from that table we can get the last inserted record id will be like this

SELECT SCOPE_IDENTITY()

OR

But this is not a safe technique:

SELECT MAX(Id) FROM Ticket

OR

This is also not a safe technique:

SELECT TOP 1 Id FROM Ticket ORDER BY Id DESC
Murder answered 25/9, 2012 at 11:26 Comment(2)
Your second and third suggestions are not safe under conditions of concurrency.Pulver
This will work but there will be a problem when simultaneously more than one entry is inserted in the table. e.g., At the time you fetch the record, another record is inserted in-between then you wont get the correct result so this is under condition of concurrency...Hope now you are clear..:)...@DavidAMurder
I
4

You should use SCOPE_IDENTITY() to get last primary key inserted value on your table. I guess it should be the ID value. Once you have it, do a SELECT using this ID and there you have it.

There is also @@IDENTITY but there are some differences using one or the another that could lead to inaccuracies on the values.

Check these detailed articles for more insights, a detailed description on how to use them, why they are different and some demo code:

Imprimis answered 25/9, 2012 at 11:26 Comment(0)
A
4

For SQL Server before 2008 R2 Service Pack 1 (Link):

You may receive incorrect values when using SCOPE_IDENTITY() and @@IDENTITY

In that case, the OUTPUT clause is the safest mechanism:

DECLARE @InsertedRows AS TABLE (Id int)
DECLARE @NewId AS INT
INSERT INTO HumanResources.Employees
  ( /* column names */)
OUTPUT Inserted.Id INTO @InsertedRows
  VALUES (/* column values */)
SELECT @NewId = Id FROM @InsertedRows
Areopagus answered 27/9, 2012 at 10:34 Comment(1)
Is this needed within a transaction?Oakie
F
0

add auto increement Field in your table like.... index (INT,AUTO INCREEMENT) then before insert or any operation done c get your last record by getting max(index)

Fiorenze answered 6/6, 2018 at 19:27 Comment(1)
Please fix the syntax to let people understand and try what you are suggesting.Panjabi
N
0

this might also helpful in some scenarios

SELECT Top 1 CAST(Id AS int) as ID from table ORDER BY [Id] DESC;
Notate answered 30/11, 2023 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.