在sql视图上更新数据时更新第三个表

时间:2018-05-18 13:51:02

标签: sql-server tsql view database-trigger

我有三张桌子:

CREATE TABLE tblEmployee1  
(  
 Id int Primary Key,  
 Name nvarchar(30),  
 Gender nvarchar(10),  
 DepartmentId int  
) 

CREATE TABLE tblDepartment1  
(  
 DeptId int Primary Key,  
 DeptName nvarchar(20)  
)

CREATE TABLE tblEmployee  
(  
 Id int Primary Key,  
 Name nvarchar(30),  
 Gender nvarchar(10),  
 DepartmentId int,  
 DeptName nvarchar(20)
) 

其中两个人加入了一个观点:

Create view ViewEmployeeDetails1  
as  
Select Id, Name, Gender,DepartmentId, DeptName  
from tblEmployee1  
join tblDepartment1  
on tblEmployee1.DepartmentId = tblDepartment1.DeptId

我创建了触发器,以便在更新视图时 使用数据触发器触发并使用视图中的数据更新第三个表(tblEmployee),而不使用重复记录。 触发剂量似乎在更新视图时将值插入到tblEmployee。你能不能帮我解决问题,不知道它的发展方向 我的触发器在下面先谢谢。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[Update_Employee]
   ON  dbo.ViewEmployeeDetails1 
   INSTEAD OF UPDATE
AS 
BEGIN
insert into dbo.tblEmployee  
([Id], [Name], [Gender], [DepartmentId], [DeptName])

SELECT  i.[Id],i.[Name], i.[Gender], i.[DepartmentId], i.[DeptName] 

        FROM   dbo.ViewEmployeeDetails1  t
       INNER JOIN i
        ON t.Id = i.Id 
        WHERE i.Id IS  NOT NULL
end

1 个答案:

答案 0 :(得分:0)

表格中没有DeptName,所以您似乎想要:

insert into dbo.tblEmployee  ([Id], [Name], [Gender], [DepartmentId])
    SELECT  i.[Id], i.[Name], i.[Gender], i.[DepartmentId]
    FROM inserted i
    WHERE i.Id IS  NOT NULL
end;