Search code examples
sqlsql-servertriggerssql-server-2019

Trigger to delete the record from the table if it exists in it


I have the following table and table employee_assignment_future, which has the same columns.

CREATE TABLE dbo.employee_assignment (
    employee_id BIGINT,
    department_id BIGINT,
    job_title_id BIGINT,
    manager_id BIGINT,
    effective_start_date SMALLDATETIME,
    effective_end_date SMALLDATETIME,
    action_code VARCHAR(60)
);

I need a trigger that checks if a employee_id and department_id and job_title_id and manager_id exists in employee_assignment_future whenever the record from employee_assignment is UPDATED, and if so to delete it from employee_assignment_future. These 4 id's are foreign keys.

I came up with something like this:

CREATE OR ALTER TRIGGER t_v_employee_assignment_update3 on employee_assignment
AFTER UPDATE
AS
BEGIN           
    DECLARE @emp_id BIGINT = (SELECT employee_id from inserted)
    DECLARE @dep_id BIGINT = (SELECT department_id from inserted)
    DECLARE @job_id BIGINT = (SELECT job_title_id from inserted)
    DECLARE @man_id BIGINT = (SELECT manager_id from inserted)

    
    DELETE FROM employee_assignment_future
    WHERE @emp_id = employee_assignment_future.employee_id 
    AND @dep_id = employee_assignment_future.department_id
    AND @job_id = employee_assignment_future.job_title_id
    AND @man_id = employee_assignment_future.manager_id
END;

SELECT * FROM employee_assignment_future
SELECT * FROM employee_assignment

UPDATE employee_assignment
SET employee_id = 4, department_id = 2, job_title_id = 8, manager_id = 3, effective_start_date ='2019-11-13 00:00:00', effective_end_date = NULL, action_code = NULL
WHERE employee_id = 64;

However, it's not deleting anything from employee_assignment_future, and not updating anything in employee_assignment.


Solution

  • A simple DELETE + JOIN should detect whether the record exists in the future and can then be deleted.

    The following delete can be the entire body of your trigger.

        DELETE F
        FROM employee_assignment_future F
        INNER JOIN Inserted I
            ON I.employee_id = F.employee_id 
            AND I.department_id = F.department_id
            AND I.job_title_id = F.job_title_id
            AND I.manager_id = F.manager_id;
    

    Note: You can't assume Inserted (or Deleted) have only a single row. You need to use set based operations and handle it having 0-N rows.