SQL Server如何更改视图,以便在插入表时不会产生重复?

时间:2018-12-14 14:18:07

标签: sql sql-server view triggers duplicates

我有见识

CREATE VIEW v1 AS
SELECT [EmployeeNo.],
       SUM([HoursTaken]) AS HoursTaken
FROM [dbo].[HolidayRequestForm]
GROUP BY [EmployeeNo.]

我想将此视图的输出放入表中。 使用

INSERT INTO [dbo].[Employees] 

SELECT * FROM v1;

哪种产品

EmployeeID  | HoursRequested |  
------------+----------------+
1           | 8              |     
2           | 16             |     
3           | 8              | 

我将此视图与触发器配合使用,因此当[dbo]。[HolidayRequestForm]更新或插入新行时,它将在我的表[dbo]上产生重复的行。[雇员]

如何获取它以仅更新表[dbo]。[员工] 而不是不会产生重复?

2 个答案:

答案 0 :(得分:1)

您正在寻找Merge

  

根据与源表的联接结果在目标表上执行插入,更新或删除操作。例如,您可以根据另一个表中的差异通过在一个表中插入,更新或删除行来同步两个表。

MERGE [dbo].[Employees]  AS target  
USING (SELECT [EmployeeNo.], HoursTaken FROM v1) 
    AS source ([EmployeeNo.], HoursTaken)  
ON (target.EmployeeID = source.[EmployeeNo.])  
WHEN MATCHED THEN   
    UPDATE SET HoursRequested = source.HoursTaken  
WHEN NOT MATCHED THEN  
    INSERT (EmployeeID , HoursRequested)  
    VALUES (source.[EmployeeNo.], source.HoursTaken)  

无论如何,在每次视图更新时更新孔表都不是一个好主意。

答案 1 :(得分:0)

尝试此查询

 MERGE EMPLOYEES E 
using v1 
ON E.employeeid = v1.employeeno 
WHEN matched THEN 
  UPDATE SET E.hoursrequested = v1.hourstaken 
WHEN NOT MATCHED BY TARGET THEN 
  INSERT (employeeid, 
          hoursrequested) 
  VALUES (v1.employeeno, 
          v1.hourstaken);

有关更多信息,https://www.essentialsql.com/introduction-merge-statement/