0

Can someone please help me converting this into SQL server trigger.

Create a trigger that will cause an error when an update occurs that would result in a salary increase greater than ten percent of the current salary.

CREATE TRIGGER RAISE_LIMIT
     AFTER UPDATE OF SALARY ON EMPLOYEE
     REFERENCING NEW AS N OLD AS O
     FOR EACH ROW
     WHEN (N.SALARY > 1.1 * O.SALARY)
            SIGNAL SQLSTATE '75000' SET MESSAGE_TEXT='Salary increase>10%' 
1
  • What is the primary key of the table, you will need to join inserted and deleted based on that Commented May 16, 2021 at 5:48

1 Answer 1

1

In SQL Server, every trigger only runs once per statement, not per row, and the pseudo-tables inserted and deleted contain, respectively, the new and old versions of the rows. You must join these on the primary key to match up the versions.

Remember that these tables may contain multiple or no rows. The UPDATE function can tell you if a column was present in the UPDATE command, it will not tell you whether any rows changed.

The trigger runs within the same transaction as the UPDATE, and an error will cause an immediate rollback of all rows. Do not attempt to rollback yourself, this will cause spurious transactional errors. Instead use THROW.

The docs are located here, you should consult them for further syntax.

CREATE TRIGGER RAISE_LIMIT ON EMPLOYEE
AFTER UPDATE
AS

IF (UPDATE(SALARY)
  AND EXISTS (SELECT 1
    FROM inserted i
    JOIN deleted d ON d.ID = i.ID
    WHERE i.SALARY > 1.1 * d.SALARY))
BEGIN
    THROW 75000, N'Salary increase > 10%', 0;
END;

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

Comments

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.