2

让我解释一下我的情况。假设我的“活动”表中有 10 条记录,其中包含“EstimatedDate”列。每条记录都是唯一的,并且具有不同的“EstimatedDate”。这 10 条记录都属于一个项目,具有相同的“ProjectId”。如果我更改一行的“EstimatedDate”,它应该自动更改表中具有相同“ProjectId”的以下行。

4

1 回答 1

2
CREATE TRIGGER dbo.Activities_Update
ON dbo.Activities
AFTER UPDATE
AS
BEGIN
  SET NOCOUNT ON;
  UPDATE a
    SET EstimatedDate = i.EstimatedDate
    FROM dbo.Activities AS a
    INNER JOIN inserted AS i
    ON a.ProjectId = i.ProjectId
    WHERE a.EstimatedDate <> i.EstimatedDate;
END
GO

虽然您的UPDATE陈述不太可能是这样的:

UPDATE Activities SET EstimatedDate = CASE
  WHEN ActivityID = 1 THEN GETDATE()
  WHEN ActivityID = 2 THEN DATEADD(DAY, 1, GETDATE()) END
WHERE ProjectID = 1;

如果你想使用 的MAX日期inserted,你可以说:

CREATE TRIGGER dbo.Activities_Update
ON dbo.Activities
AFTER UPDATE
AS
BEGIN
  SET NOCOUNT ON;

  ;WITH i AS (SELECT ProjectId, d = MAX(EstimatedDate)
    FROM inserted GROUP BY ProjectId)
  UPDATE a
    SET EstimatedDate = i.d
    FROM dbo.Activities AS a
    INNER JOIN i
    ON a.ProjectId = i.ProjectId
    WHERE a.EstimatedDate <> i.d;
END
GO

后者未经测试。

于 2012-04-23T18:24:03.757 回答