我有两个表一个Products和Products_audit,我想使用Products_audit像audit table,所以我想使用触发器更新后。我写了触发器,但无法理解如何连接两个表'Inserted'和'Deleted'
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
请帮我写一下strtes string
FROM deleted
inserted
inner join deleted d on i.id = d.id
END
因为我没有得到如何以正确的方式编写它们。
答案 0 :(得分:4)
好的,所以如果你想要做的就是将新旧版本的行放入审核表中,那么你不想要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
我认为你需要的是一个额外的专栏,至少在你的审计表上,表明&#34;在更新之前&#34;并且&#34;更新后。&#34;我们称之为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