SQL 触发器 - 如何测试操作?
我的触发器在插入、更新和删除时触发。我需要从适当的内存表中插入(插入、删除
),具体取决于哪个操作触发了触发器。由于在 INSERT
上仅填充 inserted
或在 DELETE
上填充 deleted
我想我可以只进行插入,如果有没有争吵,我很好。
但是,UPDATE
会填充两个表。我只想要 UPDATE
上 deleted
的值。我尝试使用 UPDATE(column)
函数测试更新,但即使在 INSERT
上也会返回 TRUE
。那么,如何测试UPDATE
?
ALTER TRIGGER CREATE_tableAudit
ON dbo.table
FOR INSERT, UPDATE, DELETE
AS
BEGIN
IF(UPDATE([column1]))--returns true on INSERT :(
BEGIN
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
SELECT * from deleted --update
END
ELSE
BEGIN
--only inserted is populated on INSERT, visa-versa with DELETE
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
select * from inserted --insert
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
select * from deleted --delete
END
My trigger fires on INSERT, UPDATE and DELETE
. I need to insert from the appropriate in memory table (inserted, deleted
) depending upon which operation triggered the trigger. Since only inserted
is populated on INSERT
or deleted
on DELETE
I figure I can just do an insert and if there's no rows and I'm good.
But, UPDATE
populates both tables. I only want the values from deleted
on UPDATE
. I tried testing for update using UPDATE(column)
function, but this returns TRUE
even on INSERT
. So, how can I test for UPDATE
?
ALTER TRIGGER CREATE_tableAudit
ON dbo.table
FOR INSERT, UPDATE, DELETE
AS
BEGIN
IF(UPDATE([column1]))--returns true on INSERT :(
BEGIN
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
SELECT * from deleted --update
END
ELSE
BEGIN
--only inserted is populated on INSERT, visa-versa with DELETE
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
select * from inserted --insert
INSERT INTO [dbo].[tableAudit]
([column1]
,[CreateDate]
,[UpdateDate])
select * from deleted --delete
END
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要测试 UPDATE,请在
Inserted
和Deleted
表中查找相同的主键值。To test for UPDATE, look for identical primary key values in both the
Inserted
andDeleted
tables.假设行的主键没有更改,您可以通过在主键字段上连接 Inserted 和 Deleted 表来查找更新的行。如果连接这两个表产生行,那么您可以放心地假设这些行已更新。
如果更新确实更改了行的主键,那么您最好将其视为两个操作:删除和插入。
Assuming that the primary keys of rows didn't change, you can find updated rows by joining the Inserted and Deleted tables on the primary key field(s). If joining these two tables produces rows, then you can safely assume that those rows were updated.
If an update does change the primary key of a row, then you're probably better off just treating it as two operations, a delete and an insert.
以下内容对于触发器很有用:
查询中的 * 可以更改为仅包含您想要比较的字段;如果源表中的自动编号发生更改,则可以排除它。
检查已插入:
检查是否已更新:
检查是否已删除:
The following has been useful to in triggers:
The * in the queries could be changed to include only fields you want to have compared; could exclude the autonumber if it changes in the source table.
To check for Inserted:
To check for Updated:
To check for Deleted: