Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Identity of Last Updated Row in SQL Server

@@IDENTITY returns the ID of the last row inserted, I want to retrieve the ID of the last row updated.

Here is my query:

UPDATE [Table] 
SET Active = 1, 
    Subscribed = 1, 
    RenewDate = GETDATE(),
    EndDate = DATEADD(mm,1,getdate()),
WHERE SC = @SC
  AND Service = @Ser

How do I get the ID of this updated row?

The column is called TableID and I'm not using it in the query.

like image 593
HelpASisterOut Avatar asked Apr 08 '14 08:04

HelpASisterOut


People also ask

How do I find the last updated record ID in SQL?

Go for After Insert/update trigger. It will always give you the last inserted/updated record ,from the dynamic table called Inserted... Query: Select * from Inserted.

How do I get last inserted record Identity in SQL Server?

Use @@IDENTITY to Return the Last-Inserted Identity Value in SQL Server. In SQL Server, you can use the T-SQL @@IDENTITY system function to return the last-inserted identity value in the current session. Note that it returns the last identity value generated in any table in the current session.

How can I tell when a SQL table was last updated?

SELECT name AS TableName, create_date AS CreatedDate, modify_date as ModifyDate FROM sys. tables order by ModifyDate; ...will tell me the last time a table was created and modified (from a DDL perspective).


2 Answers

You cannot retrieve an ID since there is no ID being inserted.....

But you can:

  1. just query the table using the same criteria as in your UPDATE:

    SELECT TableID 
    FROM dbo.Table
    WHERE SC = @SC AND Service = @Ser  -- just use the same criteria
    
  2. use the OUTPUT clause on the UPDATE to get that info:

    UPDATE [Table] 
    SET Active = 1, 
        Subscribed = 1, 
        RenewDate = GETDATE(),
        EndDate = DATEADD(mm,1,getdate())
    OUTPUT Inserted.TableId       -- output the TableID from the table
    WHERE SC = @SC AND Service = @Ser
    

Read more about the OUTPUT clause on Technet - it can be used on INSERT and DELETE as well

like image 65
marc_s Avatar answered Sep 28 '22 09:09

marc_s


you can try using this:

OUTPUT INSERTED.TableID 

in your code it would look like this:

    UPDATE [Table] 
    SET Active = 1, 
        Subscribed = 1, 
        RenewDate = GETDATE(),
        EndDate = DATEADD(mm,1,getdate())
OUTPUT INSERTED.TableID 
    WHERE SC = @SC
      AND Service = @Ser

Hope this helps.

like image 28
Mike Avatar answered Sep 28 '22 11:09

Mike