Asp.net 基于辅助表中的行更新主表
我有一个employee draw类型的应用程序,表如下所示:Asp.net 基于辅助表中的行更新主表,asp.net,sql-server,Asp.net,Sql Server,我有一个employee draw类型的应用程序,表如下所示: Employee (ID, name, selectionCount) Selections (employeeID, ipAddress) 现在,我需要一个更新查询,该查询将计算每个employeeID(具有唯一的IPAddress)的选择数,并更新表Employee中的selectionCount列。不是SQL Server专家,但类似的操作应该可以: update Employee a set selectionCo
Employee (ID, name, selectionCount)
Selections (employeeID, ipAddress)
现在,我需要一个更新查询,该查询将计算每个employeeID(具有唯一的IPAddress)的选择数,并更新表Employee中的selectionCount列。不是SQL Server专家,但类似的操作应该可以:
update Employee a
set selectionCount = (select count(*)
from Selections
where employeeID = a.ID)
WITH SelectionCounts(EmployeeId, SelectionCount)
AS
(
SELECT s.EmployeeId, COUNT(DISTINCT IpAddress) AS SelectionCount
FROM Selections s
GROUP BY s.EmployeeId
)
UPDATE Employee
SET SelectionCount = sc.SelectionCount
FROM SelectionCounts sc
WHERE ID = sc.EmployeeId
顺便说一句,我想你知道设计有点非规范化,这在某些情况下可能是不可取的。类似的方法应该可以:
update Employee a
set selectionCount = (select count(*)
from Selections
where employeeID = a.ID)
WITH SelectionCounts(EmployeeId, SelectionCount)
AS
(
SELECT s.EmployeeId, COUNT(DISTINCT IpAddress) AS SelectionCount
FROM Selections s
GROUP BY s.EmployeeId
)
UPDATE Employee
SET SelectionCount = sc.SelectionCount
FROM SelectionCounts sc
WHERE ID = sc.EmployeeId
未对其进行测试,因此语法可能不完全正确。采用najmeddine解决方案后,您可以将该代码放入SQL Server中Selections表的insert和/或update触发器中:
update Employee
set selectionCount = (select count(distinct ipAddress)
from Selections
where Selections.emmployeeID = Employee.ID)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER UpdateSelectionCount ON Selections
AFTER UPDATE, INSERT
AS
BEGIN
SET NOCOUNT ON
UPDATE
Employee
SET
selectionCount = (SELECT
COUNT(DISTINCT ipAddress)
FROM
Selections
WHERE
Selections.EmployeeID = Employee.ID)
END
GO