My application inserts some data into a table.
insert into this_Table (id, value, value)
I have then created a trigger that does a simple insert, into a different table with a primary key.
insert into temp_wc_triggertest values ('test', GETDATE())
My problem is then, the application tries to look for scope_identity
, from the first insert. However, it gets overwritten by the trigger, which changes the scope identity to the primary key of temp_wc_triggertest
.
How can I stop the trigger overwriting scope_identity
?
I realise there is not much code to help here, which would normally be classed as a bad question, but I don't have permission to access to the full application code at the moment, so I am hoping this is answerable as is.
This is on SQL Server 2008 R2
EDIT: I have looked at the code, and it does use scope_identity
SCOPE_IDENTITY() : returns the last identity value generated in the current scope (i.e. stored procedure, trigger, function, etc). IDENT_CURRENT() : returns the last identity value for a specific table.
The SCOPE_IDENTITY() function returns the null value if the function is invoked before any INSERT statements into an identity column occur in the scope. Failed statements and transactions can change the current identity for a table and create gaps in the identity column values.
@@Identity: It will return the last identity value generated in a connection, regardless of the table in which it was generated or the scope of the Insert statement that generated the identity. Scope_Identity(): It will return the last identity value generated in a connection, within the scope of the Insert query.
SCOPE_IDENTITY() returns the value from the insert into the user table, whereas @@IDENTITY returns the value from the insert into the replication system table. Use SCOPE_IDENTITY() for applications that require access to the inserted identity value.
Your client is most certainly using @@IDENTITY instead of SCOPY_IDENTITY()
Here is a SQL Fiddle with some code you can test on.
SQL Fiddle
MS SQL Server 2008 Schema Setup:
create table T1(ID int identity(1,1));
create table T2(ID int identity(1000, 1));
go
create trigger tr_T1 on T1 for insert
as
insert into T2 default values;
Query:
insert into T1 default values
select @@identity as "@@identity",
scope_identity() as "scope_identity()"
Results:
| @@IDENTITY | SCOPE_IDENTITY() |
---------------------------------
| 1000 | 1 |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With