0

I want to update an entity in a table after a insert is done in another table. Here my current trigger which doesn't work.

ALTER TRIGGER [dbo].[UpdateLastValues]  
ON [dbo].[MeasureValues] FOR INSERT   
AS BEGIN

SET NOCOUNT ON;

DECLARE @MyValue AS nvarchar;
DECLARE @MyTimestamp AS datetimeoffset;
DECLARE @MyId AS nvarchar;

SELECT @MyValue = Value FROM INSERTED;
SELECT @MyTimestamp = Timestamp FROM INSERTED;
SELECT @MyId = MeasurePointId FROM INSERTED;

UPDATE [dbo].[MeasurePoints] SET  [dbo].[MeasurePoints].[LastValue] = @MyValue, [dbo].[MeasurePoints].[LastEdit] = @MyTimestamp WHERE [dbo].[MeasurePoints].[Id] = @MyId
END

Measure Values receive new values. The latest values should be saved in MeasurePoints LastValue Column.

2
  • "doesn't work" is not an error message or a useful problem statement. Please tell us exactly what happens - e.g. do you get an error, or does it not produce the expected result? It might help to give us an example of the input data, and then what the desired outcome should be. Commented Dec 21, 2018 at 9:07
  • 1
    Your trigger has a major flaw here, it assumes that your table will only ever have 1 row inserted at a time. Commented Dec 21, 2018 at 9:09

1 Answer 1

4

Change the Trigger from FOR INSERT to AFTER INSERT.

Also, I have made some changes in the Code to remove the Unnecessary codes

ALTER TRIGGER [dbo].[UpdateLastValues]  
ON [dbo].[MeasureValues] AFTER INSERT   
AS BEGIN

SET NOCOUNT ON;

UPDATE MP
    SET
        LastValue = INSERTED.[Value],
        LastEdit = INSERTED.[Timestamp]
    FROM [dbo].[MeasurePoints] MP
        INNER JOIN Inserted
            ON MP.id = Inserted.MeasurePointId

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

1 Comment

FOR and AFTER are the same in SQL Server, so changing FOR to AFTER makes no difference (See FOR | AFTER in CREATE TRIGGER (Transact-SQL)). Changing the trigger to a dataset approach though, now that makes a big difference. :)

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.