SQL Server 中的表历史触发器?
我想创建一个触发器,用插入的值以及更新前后的值写入历史表。我还想包含尽可能多的有关执行更新的帐户的信息。我如何将帐户信息包含在触发器中?
这是我到目前为止所得到的:
CREATE TRIGGER [update_history] ON MyTable
FOR UPDATE
AS
INSERT MyTable_History (id, BudgetNumber, PositionNumber, ModifiedDate, action, userId)
SELECT id, BudgetNumber, PositionNumber, GETDATE(), 'BEFORE UPDATE', '???'
FROM deleted
INSERT MyTable_History (id, BudgetNumber, PositionNumber, ModifiedDate, action, userId)
SELECT id, BudgetNumber, PositionNumber, GETDATE(), 'AFTER UPDATE', '???'
FROM inserted
我该用什么来代替“???”?
I'd like to create a trigger that writes to a history table with inserted values and before and after update values. I would also like to include as much information about the account doing the update as is possible. How would i include the account information in my trigger?
Here is what I have so far:
CREATE TRIGGER [update_history] ON MyTable
FOR UPDATE
AS
INSERT MyTable_History (id, BudgetNumber, PositionNumber, ModifiedDate, action, userId)
SELECT id, BudgetNumber, PositionNumber, GETDATE(), 'BEFORE UPDATE', '???'
FROM deleted
INSERT MyTable_History (id, BudgetNumber, PositionNumber, ModifiedDate, action, userId)
SELECT id, BudgetNumber, PositionNumber, GETDATE(), 'AFTER UPDATE', '???'
FROM inserted
What do i put in place of the '???'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果每个用户都有一个帐户,您可以使用
SYSTEM_USER
函数来确定当前用户。但是,如果您的所有连接都通过代理帐户(就像大多数网站设置中的典型情况一样),那么您必须依赖传递到 Update 语句的正确 userId:If each user has an account, you can use the
SYSTEM_USER
function to determine the current user. However, if all your connections go through a proxy account, as is typical in most web site setups, then you have to rely on the proper userId being passed to the Update statement:FWIW,如果您使用 SQL Server 2008,那么有比编写触发器来跟踪数据更改更好的选择。请查看更改数据捕获。
FWIW, if you are using SQL Server 2008, there is a much better alternative than writing triggers to track data changes. Take a look at Change Data Capture.
使用
ORIGINAL_LOGIN()
您可以在此处查看其功能的进一步定义
SQL Server - 当前用户名
use
ORIGINAL_LOGIN()
you can see further definition of what it does here
SQL Server - current user name