简体   繁体   中英

How to get last inserted row from a table?

I tried below query but results in more than one row and [SCOPE_IDENTITY] as NULL.What are the alternates?

  SELECT TOP 1000 
    [RTID],xxx,xxx
   FROM [RouteTiming]
    GO
    SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
    GO
    SELECT @@IDENTITY AS [@@IDENTITY];
    GO

Depending on the server version (SQL Server 2005+) you can use the OUTPUT clause:

INSERT INTO tablename (column names)
OUTPUT --this is where you put your select statement to get returned IDs etc.
VALUES (values in here, or you can use a select statememt as per usual)

MSDN Article: OUTPUT Clause (Transact-SQL)

If you are inside a stored procedure or a function, you can use INSERTED table (there is also a DELETED table) which is stored in memory until the scope is completed.
Once you have performed your insert, you can join the inserted table just like any other as long as it is within the same scope. I believe the inserted table has been around since SQL Server 2000, but it is definitely in 2005+.

MSDN Examples: Use the inserted and deleted Tables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM