IDENTITY

CREATE TABLE dbo.logging_table(log_id INT IDENTITY(1,1) PRIMARY KEY, 
                               log_message VARCHAR(255))

CREATE TABLE dbo.person(person_id INT IDENTITY(1,1) PRIMARY KEY, 
                        person_name VARCHAR(100) NOT NULL)
GO;

CREATE TRIGGER dbo.InsertToADifferentTable ON dbo.person  
AFTER INSERT  
AS
    INSERT INTO dbo.logging_table(log_message)
    VALUES('Someone added something to the person table')
GO;

INSERT INTO dbo.person(person_name)
VALUES('John Doe')    

SELECT @@IDENTITY;

無論範圍如何,這都將在同一連線上返回最近新增的標識。在這種情況下,無論 logging_table 上標識列的當前值是什麼,假設 SQL Server 例項上沒有發生其他活動,並且沒有其他觸發器從此插入觸發。