这是与Microsoft sql Server 2008.
我有2个表,Employee和EmployeeResult,我试图在EmployeeResult上写一个简单的INSERT触发器,每次INSERT都完成到EmployeeResult中,例如:
(杰克,200,销售)
(简,300,营销)
(约翰,400,工程)
它应该查找名称,部门条目对,如
(杰克,销售),
(简,营销),
(John,Engineering)
在Employee表中,如果此类员工不存在,则应将其插入员工表中.
我有这个与未知数如何修复“???”:
CREATE TRIGGER trig_Update_Employee ON [EmployeeResult] FOR INSERT AS IF EXISTS (SELECT COUNT(*) FROM Employee WHERE ???) BEGIN INSERT INTO [Employee] (Name,Department) VALUES (???,???) END
请帮忙,谢谢提前
架构:
Employee -------- Name,varchar(50) Department,varchar (50) EmployeeResult -------------- Name,varchar(50) Salary,int Department,varchar (50)
解决方法
您希望利用在触发器上下文中可用的插入逻辑表.它匹配要插入的表的模式,并包括要插入的行(在更新触发器中,您可以分别访问表示新数据和原始数据的插入和删除的逻辑表.)
因此,要插入当前不存在的员工/部门对,您可以尝试以下操作.
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