如何使用触发器记录 SQL 服务器中的更改?
How to Use Trigger to Log Changes in SQL Server?
Users
table:
LoginLog
table:
当 Users
table LastLogonTime
列更新并插入一行时,如何将名称、密码、LastLogonTime 记录到 LoginLog
table?
您需要一个相当简单的触发器来更新 Users
table。更棘手的部分是意识到触发器 只为每个语句触发一次 这一事实 - 这样的语句可能会更新 多行 这将然后在你的 Inserted
和 Deleted
伪 table 触发器中。
您需要编写触发器以意识到 这种基于集合的方式并正确处理它。为了能够正确地 link 旧值和新值,您的 table Users
必须具有 正确的主键(您没有提及任何相关内容)- 类似于 UserId
之类的东西。
尝试这样的事情:
CREATE TRIGGER dbo.trg_LogUserLogon
ON dbo.Users
FOR UPDATE
AS
-- inspect the Inserted (new values, after UPDATE) and Deleted (old values, before UPDATE)
-- pseudo tables to find out which rows have had an update in the LastLogonTime column
INSERT INTO dbo.LoginLog (Name, Password, LastLogonTime)
SELECT
i.Name, i.Password, i.LastLogonTime
FROM
Inserted i
INNER JOIN
-- join the two sets of data on the primary key (which you didn't specify)
-- could be i.UserId = d.UserId or something similar
Deleted d on i.PrimaryKey = d.PrimaryKey
WHERE
-- only select those rows that have had an update in the LastLogonTime column
i.LastLogonTime <> d.LastLogonTime
但也请无论如何接受@Larnu关于不EVER存储密码的评论以纯文本形式考虑!这确实是一件非常糟糕的事情,需要不惜一切代价避免。
Users
table:
LoginLog
table:
当 Users
table LastLogonTime
列更新并插入一行时,如何将名称、密码、LastLogonTime 记录到 LoginLog
table?
您需要一个相当简单的触发器来更新 Users
table。更棘手的部分是意识到触发器 只为每个语句触发一次 这一事实 - 这样的语句可能会更新 多行 这将然后在你的 Inserted
和 Deleted
伪 table 触发器中。
您需要编写触发器以意识到 这种基于集合的方式并正确处理它。为了能够正确地 link 旧值和新值,您的 table Users
必须具有 正确的主键(您没有提及任何相关内容)- 类似于 UserId
之类的东西。
尝试这样的事情:
CREATE TRIGGER dbo.trg_LogUserLogon
ON dbo.Users
FOR UPDATE
AS
-- inspect the Inserted (new values, after UPDATE) and Deleted (old values, before UPDATE)
-- pseudo tables to find out which rows have had an update in the LastLogonTime column
INSERT INTO dbo.LoginLog (Name, Password, LastLogonTime)
SELECT
i.Name, i.Password, i.LastLogonTime
FROM
Inserted i
INNER JOIN
-- join the two sets of data on the primary key (which you didn't specify)
-- could be i.UserId = d.UserId or something similar
Deleted d on i.PrimaryKey = d.PrimaryKey
WHERE
-- only select those rows that have had an update in the LastLogonTime column
i.LastLogonTime <> d.LastLogonTime
但也请无论如何接受@Larnu关于不EVER存储密码的评论以纯文本形式考虑!这确实是一件非常糟糕的事情,需要不惜一切代价避免。