SQL Server 2008 - Help writing simple INSERT Trigger

前端 未结 3 1728
北荒
北荒 2020-11-29 10:53

This is with Microsoft SQL Server 2008.

I\'ve got 2 tables, Employee and EmployeeResult and I\'m trying to write a simple INSERT trigger on EmployeeResult that does

3条回答
  •  情书的邮戳
    2020-11-29 11:35

    You want to take advantage of the inserted logical table that is available in the context of a trigger. It matches the schema for the table that is being inserted to and includes the row(s) that will be inserted (in an update trigger you have access to the inserted and deleted logical tables which represent the the new and original data respectively.)

    So to insert Employee / Department pairs that do not currently exist you might try something like the following.

    CREATE TRIGGER trig_Update_Employee
    ON [EmployeeResult]
    FOR INSERT
    AS
    Begin
        Insert into Employee (Name, Department) 
        Select Distinct i.Name, i.Department 
        from Inserted i
        Left Join Employee e
        on i.Name = e.Name and i.Department = e.Department
        where e.Name is null
    End
    

提交回复
热议问题