@@Indentity and Scope_Indentity?
In SQL Server, @@IDENTITY and SCOPE_IDENTITY() are special functions that are used to retrieve the last generated identity value within the current session or scope. They are commonly used when working with tables that have an identity column, which is a column that automatically generates unique values.
Here's an explanation of each function:
-
@@IDENTITY:
-
@@IDENTITY is a system function that returns the last identity value generated in the current session across all tables.
-
It is not limited to the current scope or specific table.
-
It returns the last identity value regardless of which table or scope generated it.
-
It is important to note that if there are triggers on the table that insert into another table with an identity column, @@IDENTITY will return the last identity value generated by any insert operation within the session, including those triggered by other tables.
-
SCOPE_IDENTITY():
-
SCOPE_IDENTITY() is a function that returns the last identity value generated within the current scope (e.g., a stored procedure, trigger, or batch) and by the statement that caused the identity value to be generated.
-
It is more precise and reliable when you specifically want to retrieve the last identity value within the current scope
-
It is not affected by inserts triggered by other tables or triggers.
-
It only returns the last identity value generated by the statement that caused the identity value to be generated. For example, if an INSERT statement triggers multiple rows to be inserted, SCOPE_IDENTITY() will return the identity value of the last inserted row within that statement.
Here's an example to illustrate their usage:
-- Assuming there is a table called "MyTable" with an identity column "ID"
-- Insert a row and retrieve the last identity value using @@IDENTITY
INSERT INTO MyTable (Column1, Column2) VALUES ('Value1', 'Value2')
SELECT @@IDENTITY
-- Insert another row and retrieve the last identity value using SCOPE_IDENTITY()
INSERT INTO MyTable (Column1, Column2) VALUES ('Value3', 'Value4')
SELECT SCOPE_IDENTITY()
In the above example, the first SELECT statement with @@IDENTITY will return the last identity value generated by any insert operation in the current session, including the insert triggered by the second INSERT statement. However, the second SELECT statement with SCOPE_IDENTITY() will only return the last identity value generated by the second INSERT statement itself.