Reputation: 6720
I have a table let us say TableA
. I have created a trigger
which is fired on Insertion, Update or Deletion of record in TableA
and inserts record in another table let us say TableB
. Now where am I finding difficulty is from some of the stored procedures
of TableA
I am returning scope_identity()
of inserted record
. That must be returned from TableA's
record while I am getting it from TableB
. Is there any way to solve this issue? I want scope_identity()
from TableA
only, NOT
from TableB
. Awaiting for your valuable response.
Thanks in advance..
Upvotes: 1
Views: 122
Reputation: 772
SCOPE_IDENTITY() should work in that situation, it should be scoped to your stored proc and the insert to TableA, not the insert done in the trigger.
CREATE TABLE [dbo].[TableA](
[ID] [int] IDENTITY(1,1) NOT NULL,
[TestColumn] [nvarchar](50) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[TableB](
[ID] [int] IDENTITY(1,1) NOT NULL,
[TestColumn] [nvarchar](50) NULL
) ON [PRIMARY]
CREATE TRIGGER [dbo].[TableA_AIDU]
ON [dbo].[TableA]
AFTER INSERT,DELETE,UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO TableB ( TestColumn )
SELECT 'TableA Modified'
END
CREATE PROCEDURE [dbo].[sp_InsertToTableA]
@ID INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT TableA ( TestColumn )
SELECT 'Insert from sp_InsertToTableA'
SET @ID = SCOPE_IDENTITY()
END
The stored proc returns the ID from TableA, and the TableB insert is triggered as expected. Are you sure you're not using @@IDENTITY instead of SCOPE_IDENTITY()?
Upvotes: 1