-4

我有两个表,一个是 Products 和 Products_audit,我想像审计表一样使用 Products_audit,所以我想在更新后使用触发器。我写了触发器,但不明白如何连接两个表“已插入”和“已删除”

CREATE TRIGGER Super2
ON Products
AFTER Update
AS
BEGIN

INSERT INTO Products_audit

      (ProductID,
       ProductName,
       SupplierID,
       CategoryID,
       QuantityPerUnit,
       UnitPrice,
       UnitsInStock,
       UnitsOnOrder,
       ReorderLevel,
       Discontinued,
       Date,
       [User])

SELECT 

       ProductID,
       ProductName,
       SupplierID,
       CategoryID,
       QuantityPerUnit,
       UnitPrice,
       UnitsInStock,
       UnitsOnOrder,
       ReorderLevel,
       Discontinued,
       getdate(),
       suser_sname()

       FROM deleted

inserted 
    inner join deleted d on i.id = d.id

      END 

请帮我写下lastes字符串

FROM deleted
inserted 
    inner join deleted d on i.id = d.id

      END

因为我不知道如何以正确的方式编写它们。

4

1 回答 1

4

好的,因此,如果您只想将行的旧版本和新版本都放入审计表中,那么您不需要 a JOIN,而是需要UNION ALL.

(正如我在上面的评论中提到的,我根本不理解这个逻辑,我保证你以后意识到它有多么错误时会改变它。)

CREATE TRIGGER dbo.Super2
ON dbo.Products FOR UPDATE
AS
BEGIN

  SET NOCOUNT ON;

  INSERT dbo.Products_audit
  (
       ProductID,
       ...other columns...,
       Date,
       [User]
  )
  SELECT 
       ProductID,
       ...other columns...,
       getdate(),
       suser_sname()
    FROM deleted -- <--- ****** deleted ******
  UNION ALL
  SELECT 
       ProductID,
       ...other columns...,
       getdate(),
       suser_sname()
    FROM inserted;
END
GO

我认为您至少需要在审计表上增加一列,指示“更新前”和“更新后”。让我们称之为ChangeStatus(您也可以将其重新用于插入和删除操作):

CREATE TRIGGER dbo.Super2
ON dbo.Products FOR UPDATE
AS
BEGIN

  SET NOCOUNT ON;

  DECLARE @d DATETIME = GETDATE(), @u SYSNAME = SUSER_SNAME();

  INSERT dbo.Products_audit
  (
       ProductID,
       ...other columns...,
       ChangeStatus,
       Date,
       [User]
  )
  SELECT 
       ProductID,
       ...other columns...,
       'before update',
       @d,
       @u
    FROM deleted -- <--- ****** deleted ******
  UNION ALL
  SELECT 
       ProductID,
       ...other columns...,
       'after update',
       @d,
       @u
    FROM inserted;
END
GO
于 2013-03-28T13:27:09.927 回答