0

I'm trying to update a just inserted row in SQL with a table trigger. Below is the trigger. It seems this only updates the already inserted rows and NOT the just inserted row. What am I doing wrong?

ALTER TRIGGER [dbo].[TRG_DIM_Employee]
ON [dbo].[DIM_Employee]
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON
    UPDATE DIM_Employee
    SET ParentEmployeeKey = i.EmployeeKey
    FROM INSERTED i
    WHERE DIM_Employee.EmployeeId = i.EmployeeId
END
6
  • which version of MS SQL are you using? Commented Jun 16, 2015 at 15:11
  • Microsoft SQL Server 2012 - 11.0.5556.0 (X64) Oct 31 2014 16:50:24 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor) Commented Jun 16, 2015 at 15:17
  • Why not just have a default value in SQL? You want a trigger of overwrite even if they supply a value for ParentEmployeeKey? Commented Jun 16, 2015 at 15:51
  • Because not only the just inserted row must be changed but all rows having that particular EmployeeId must be updated. Commented Jun 17, 2015 at 7:06
  • Could you post a sample of the data in the employee table? Commented Jun 17, 2015 at 14:06

2 Answers 2

1

As far as I can recognize, this is old join syntax but is functionally equivalent. I set up a quick test but can't repro this issue, seems to work as expected.

FYI you should move to using proper JOIN syntax, this old ANSI-89 standard is already discontinued in some forms in SQL 2012.

Sign up to request clarification or add additional context in comments.

Comments

0

Your update statement is not quite right. You need to JOIN your table with the inserted table rows.

ClientID int,
ALTER TRIGGER [dbo].[TRG_DIM_Employee]
ON [dbo].[DIM_Employee]
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON

    UPDATE emp
    SET emp.ParentEmployeeKey = i.EmployeeKey
    FROM  DIM_Employee emp
    JOIN INSERTED i on emp.EmployeeId = i.EmployeeId
END

More examples of doing an update join here.

1 Comment

I've tried this and the outcome is exactly the same as the original statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.