SQL SERVER 2008 GETS THE LAST INSERTED VALUES

This is my table.

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

after pasting into this table I want to send the identifier and name by mail. how can i get the latest inserted value.

help solve this problem ...

+4
source share
3 answers

Take a look: Scope_identity

 SCOPE_IDENTITY() 

The table that has the Identity property from this table, we can get the last inserted record identifier, will look 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 
+8
source

You must use SCOPE_IDENTITY() to get the last inserted primary key value in your table. I think it should be an ID value. After that, do SELECT using this identifier, and there you have it.

There is also @@IDENTITY , but there are some differences using one or the other, which can lead to inaccurate values.

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

+4
source

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

When using SCOPE_IDENTITY () and @@ IDENTITY

In this 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 
+2
source

Source: https://habr.com/ru/post/1436129/


All Articles