在触发器中使用插入和删除的表
我想编写触发器来处理插入和删除的表。我已经编写了用于插入的触发器:
CREATE TRIGGER FILL_TABLE
ON Person FOR INSERT
AS
DECLARE @ID int
SELECT @ID = p.ID
FROM Person AS p
INNER JOIN inserted AS i ON p.ID = i.ID
DECLARE @uName char(30);
SELECT @uName = SYSTEM_USER
INSERT tblOperationLog
Values
( @uName, 'user has inserted a row with ID = ' + CONVERT(nvarchar, @ID) + '',
'Insert', CURRENT_TIMESTAMP, GETDATE() )
我想编写触发器并使用已删除的表,就像插入的表一样。但我不知道怎么做。我想检索已删除行的 ID 以填充 tblOperationLog 的第二列,但我不能。我也应该使用内部连接吗?
I want to write triggers to work with the inserted and deleted tables. I have written the trigger for inserting :
CREATE TRIGGER FILL_TABLE
ON Person FOR INSERT
AS
DECLARE @ID int
SELECT @ID = p.ID
FROM Person AS p
INNER JOIN inserted AS i ON p.ID = i.ID
DECLARE @uName char(30);
SELECT @uName = SYSTEM_USER
INSERT tblOperationLog
Values
( @uName, 'user has inserted a row with ID = ' + CONVERT(nvarchar, @ID) + '',
'Insert', CURRENT_TIMESTAMP, GETDATE() )
I want to write the trigger and use the deleted table just like the inserted one. but I don't know how. I want to retrieve the ID of the deleted rows to fill the second column of the tblOperationLog but I can't. Should I use the inner join in it too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅当仅插入一行时,您的触发器才会起作用。由于
inserted
可用作表,因此您可以从该表插入并使用所有记录。我想你正在寻找这样的东西:Your trigger will only work if only one row has been inserted. As
inserted
is available as a table, you can insert from that table and use all records. I think you're looking for something like this:在 SQL Server 中,触发器可以访问两个逻辑表
INSERTED
和DELETED
,它们与触发器定义的表具有相同的结构。两个表都将在
UPDATE
触发器上填充。INSERT
触发器只会填充INSERTED
表,DELETE
触发器只会填充DELETED
表。请参阅 MSDN。
In SQL server, a trigger has access to two logical tables
INSERTED
andDELETED
that have the same structure as the table the trigger is defined.Both tables will be filled on an
UPDATE
trigger. AnINSERT
trigger will only have theINSERTED
table filled, aDELETE
trigger will only have theDELETED
table filled.See MSDN.