Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop trigger changing scope_identity

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

like image 907
Wayneio Avatar asked Apr 08 '13 15:04

Wayneio


People also ask

What is the difference between Scope_identity () and Current_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.

What is the use of Scope_identity () function?

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.

What are identity () and Scope_identity () functions in SQL?

@@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.

What is Scope_identity in mssql?

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.


1 Answers

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 |
like image 87
Mikael Eriksson Avatar answered Sep 19 '22 00:09

Mikael Eriksson